Laravel 5.1查询生成器:获取包含搜索查询的帖子的用户


Laravel 5.1 Query Builder: get users with post whose body contains search queries

假设:

  1. 这是一个普通的博客应用程序
  2. users表具有idnameemailpassword字段
  3. posts表具有idtitlebody字段
  4. 注册了5个用户
  5. 每个用户有10个帖子
  6. 用户"有许多"帖子,发布"属于"用户

问题:

我想得到那些标题或正文包含搜索查询的帖子的"用户"。

我当前的代码:

// example of search queries
$search_queries = ['aaa', 'bbb', 'ccc'];
// column names to search in MySQL
$search_column_names = [
                        'users.name',
                        'posts.title',
                        'posts.body'
                        ];
$users = User::leftJoin('posts', 'users.id', '=', 'posts.user_id')
    ->orWhere(function($q) use ($search_queries, $search_column_names){
        foreach ($search_column_names as $key => $name) {
            $q->orWhere(function($q) use ($search_queries, $name){
                foreach ($search_queries as $key => $search_query) {
                    $q->where($name, 'like', '%' . $search_query . '%');
                }
            });
        }
    })->distinct('users.id')->get();

但我仍然有超过5个不同id的用户(最多50个)。我以为distinct(users.id)给了我一个理想的结果,但它没有起作用。

我已经在网上搜索过了,但找不到解决方案。

提前谢谢。

您可以使用原始语句。

$users = User::whereRaw("id in(
                            select distinct user_id from posts
                            where title like :query or
                            body like :query
                            )" , ["query" =>  "%" . $search_query . "%"])->get();

我找到了一个解决方案。我将posts表搜索划分为两个whereIns。谢谢

// column names to search in the database
$search_column_names = [
'users.name'
];
$users = User::
orWhere(function($q) use ($queries, $search_column_names){
    foreach ($search_column_names as $key => $name) {
        $q->orWhere(function($q) use ($queries, $name){
            foreach ($queries as $key => $value) {
                $q->orWhere($name, 'like', '%' . $value . '%');
            }
        });
    }
})
->whereIn('users.id', function($q) use ($queries){
    $q->select('user_id')
    ->from(with(new Post)->getTable())
    ->where(function($q2) use ($queries){
        foreach ($queries as $key => $value) {
            $q2->orWhere('posts.title', 'like', '%' . $value . '%');
        }
    });
}, 'or')
->whereIn('users.id', function($q) use ($queries){
    $q->select('user_id')
    ->from(with(new Post)->getTable())
    ->where(function($q2) use ($queries){
        foreach ($queries as $key => $value) {
            $q2->orWhere('posts.body', 'like', '%' . $value . '%');
        }
    });
}, 'or')
->get();