我们有一个 posts 表,user_id 是外键 例如,我想为这些用户选择帖子
$users=[1,2,13,16,17,19];
$posts = Post::whereIn('user_id', $users)->paginate(10);
但是我希望用户 1 和 2 在输出中只有两个帖子,对于其余用户来说,帖子数量没有限制。
注意:用户 1 和 2 并不总是在
数组中,并且由于条件的原因,用户 1 和 2 可能不在数组中。$users
你有办法给我吗?
您无法在单个查询中实现此目的,我们需要像这样单独进行
$users=[1,2,13,16,17,19];
// first take all the post except the two
$posts = Post::whereIn('user_id', $users)->whereNotIn('user_id', [1,2])->get()->toArray();
// then take one user 1 post in desc and limit it by 2
$userOnePost = Post::whereIn('user_id', $users)->where('user_id', 1)->limit(2)->orderBy('post.id', 'desc')->get()->toArray();
// then take one user 2 post in desc and limit it by 2
$userTwoPost = Post::whereIn('user_id', $users)->where('user_id', 2)->limit(2)->orderBy('post.id', 'desc')->get()->toArray();
// merge all the array
$allPost = array_merge(posts,$userOnePost,userTwoPost);
您可以尝试这个替代方案:
$posts = [];
$users=[1,2,13,16,17,19];
$userWithJustTwo = [1,2];
$result = array_intersect($users, $userWithJustTwo);
$posts[] = Post::whereIn('user_id', $result)->orderBy('created_at', 'desc')->take(2)->get();
$array = array_diff($users, userWithJustTwo);
$posts[] = Post::whereIn('user_id', $array)->get();
您可以使用
->take()
来做到这一点
$posts = [];
$users=[1,2,13,16,17,19];
foreach($users as $user)
{
if($user == 1 || $user == 2)
{
$posts[] = Post::where('user_id', $user)->take(2)->get();
}
else
{
$posts[] = Post::where('user_id', $user)->get();
}
}
试试这个方法:
$users = User::whereNotIn('id', [1,2])->pluck('id');
$posts = [];
$posts[] = Post::whereIn('user_id', [1,2])->take(2)->get();
$posts[] = Post::whereIn('user_id', $users)->get();
如果您想获得最新的
post
,请使用此:
$posts[] = Post::whereIn('user_id', [1,2])->latest('created_at')->take(2)->get();
您也可以像这样使用参数分组
DB::table('post')
->whereIn('user_id', $users)
->where(function ($query) {
$query->whereIn('user_id', [1,2])->limit(2)
->orWhereNotIn('user_id', [1,2]);
})
->get();