使用whereIn限制Laravel查询

时间:2019-05-07 14:10:40

标签: laravel laravel-5 laravel-5.8

所以我要查询,但是我不知道如何做到最好。 我有两节课,如下所示:

User.class

class User {
    function posts(){
        return $this->hasMany(Post::class, 'user_id');
    }
}

Post.class

class Post {
    function user(){
        return $this->belongsTo(User::class, 'user_id');
    }
}

并且在我的控制器中,我想为每个用户获取帖子,并为每个用户设置一个限制并非所有结果。所以这就是我的控制器中的内容:

function getPosts(Request $request){
    $user_ids = [1,2,3,4];

    $posts = Post::whereIn('user_id', $user_ids)->latest()->take(10)->get();
    return $posts;
} 

因此,上述获取将使我只获得10 entries from all个,而我想获得10 for each user个用户ID

2 个答案:

答案 0 :(得分:0)

您可以简单地通过子查询限制关系:

User::with(['posts' => function($query) {
    return $query->limit(10);
}]);

答案 1 :(得分:0)

可能类似于

DB::table('posts as p1')->leftJoin('posts as p2', function($join){
    $join->on('p1.id', '=', 'p2.id')
})->whereIn(p1.user_id, $user_ids)->groupBy('p1.id')->having(COUNT(*) < 10)->orderBy([id, created_at]);

将为您工作。供参考question

查询是

SELECT user_comments.* FROM user_comments
LEFT OUTER JOIN user_comments user_comments_2
ON user_comments.post_id = user_comments_2.post_id 
    AND user_comments.id < user_comments_2.id    
where user_comments.post_id in (x,x,x) 
GROUP BY user_comments.id 
HAVING COUNT(*) < 3 
ORDER BY user_id, created_at

大约在数据库查询构建器中,它就像

DB::table('user_comments as uc1')->leftJoin('user_comments as uc2', function($join){
    $join->on('uc1.post_id', '=', 'uc2.post_id')->andOn(uc1.id < uc2.id);
})->whereIn(uc1.post_id, [x,x,x])->groupBy('uc1.id')->having(COUNT(*) < 3)->orderBy([user_id, created_at]);

我希望这对您有所帮助,并为您提供一个好主意。