gpt4 book ai didi

mysql - 如何限制 Laravel 中特定外键值的行数

转载 作者:行者123 更新时间:2023-11-29 09:53:33 25 4
gpt4 key购买 nike

我们有一个 posts 表,user_id 是外键例如,我想为这些用户选择帖子

$users=[1,2,13,16,17,19];
$posts = Post::whereIn('user_id', $users)->paginate(10);

但我希望用户 1 和 2 在输出中只有两个帖子,对于其余用户,帖子数量没有限制。

Note: User 1 and 2 are not always within the $users array, and due to the condition, one or both of them may not be in the array.

你有解决办法吗?

最佳答案

您无法在单个查询中实现此目的,我们需要像这样单独进行处理

$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);

关于mysql - 如何限制 Laravel 中特定外键值的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54323254/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com