【问题标题】:Get all records which count is more than specific number获取计数大于特定数字的所有记录
【发布时间】:2021-04-12 05:44:53
【问题描述】:

这是我的例子。

我有一个属于多个作者的博客文章列表。我想获取拥有超过 3 篇博文的作者所写的所有博文。

POSTS 表

id | author_id | post_title | post_body
1  |    1      |  ...       | ...
2  |    1      |  ...       | ...
3  |    1      |  ...       | ...
4  |    2      |  ...       | ...
5  |    3      |  ...       | ...
6  |    4      |  ...       | ...
7  |    4      |  ...       | ...
8  |    4      |  ...       | ...
9  |    5      |  ...       | ...

所以,我想得到这个结果:

id | author_id | post_title | post_body
1  |    1      |  ...       | ...
2  |    1      |  ...       | ...
3  |    1      |  ...       | ...
6  |    4      |  ...       | ...
7  |    4      |  ...       | ...
8  |    4      |  ...       | ...

我怎样才能在一个雄辩的查询中写出来?

【问题讨论】:

  • 你和模特有关系吗?
  • 是的,我和作者模型有关系。
  • 作者与帖子有关系吗?
  • 是的,它有。进行此查询的最佳解决方案是什么?

标签: php sql laravel eloquent


【解决方案1】:

我必须仔细检查这是否必须以不同的方式嵌套,但这样的事情似乎可以解决问题:

Post::has('user.posts', '>', 3)->get()

试图说获取用户的帖子数量大于 3 的帖子。

如果嵌套不起作用,它会是这样的:

Post::whereHas('users', function ($q) {
    $q->has('posts', '>', 3);
})->get();

更新:

Post::whereHas('users', function ($q) {
    $q->whereHas('posts', function ($q) {
        $q->where('status', 'published');
    }, '>', 3);
})->get():

虽然看看这是否有效(不确定):

Post::whereHas('users.posts', function ($q) {
    $q->where('status', 'published');
}, '>', 3)->get();

【讨论】:

  • 这很完美,但我还有一个问题是如何使用附加参数来完成这项工作?例如按给定日期过滤?就像如何在查询的最后一点进行这项工作?当我通过其他参数过滤所有内容时。
  • 过滤什么参数,你必须具体,因为这取决于条件/过滤器的位置
  • @django11 如果您想进一步过滤帖子,只需在调用get之前添加 wheres
  • 我不知道如何使这部分工作:"$q->has('posts', '>', 3);"我想检查用户是否有超过 3 个状态为已发布的帖子。现在它只检查用户是否有超过 3 个帖子。
  • @django11 要求您使用 whereHas 而不是 has 进行“帖子”检查,已更新
【解决方案2】:

在 SQL 中,您可以使用窗口函数:

select t.*
from (select t.*, count(*) over (partition by author_id) as cnt
      from t
     ) t
where cnt >= 3
order by cnt desc, author_id

【讨论】:

    【解决方案3】:

    如果您可以/想要使用 SQL,您可以这样做:

    select *
    from POSTS
    where author_id in 
    (
      -- authors with more than 3 posts
      select author_id
      from POSTS
      group by author_id
      having count(*) > 3
    )
    

    【讨论】:

      猜你喜欢
      • 2018-09-26
      • 1970-01-01
      • 2013-12-09
      • 1970-01-01
      • 2019-09-07
      • 1970-01-01
      • 2019-06-12
      • 2020-10-19
      • 2021-11-09
      相关资源
      最近更新 更多