【问题标题】:what is the laravel eloquent equivalent of my SQL Count GroupBy query?什么是 mySQL Count Group By 查询的 laravel eloquent 等价物?
【发布时间】:2020-05-21 14:53:11
【问题描述】:

这是我的 sql 查询

SELECT COUNT(*) FROM anuncios WHERE user_id = 2 and user_id = 3 or estado = "Activo" GROUP BY user_id

导致每个 user_id 的活动“anunios”总数;

但是尝试使用 laravel eloquent 进行相同的查询会给我带来所有数据的总和,而无需按 user_id 对它们进行分组

这是我对 laravel eloquent 的查询

$anuncios = Anuncios::whereIn('user_id',$ids)->where('estado','Activo')->groupBy('user_id')->get()->count();

【问题讨论】:

  • WHERE user_id = 2 and user_id = 3 怎么可能同时为真?
  • 我使用 sql where user_id = 2 and user_id = 3 进行了查询,因为目前在我的用户表中我只有 3 个,出于实际目的,我将它们放入(因为我知道它们存在),除非查询有错误,而不是“和”应该是“或”
  • 您的代码中不需要->get() 部分。

标签: php laravel eloquent


【解决方案1】:

如果您正在调用 ->get(),那么您正在对集合执行 count()。如果您想将其作为查询运行,则需要通过删除 ->get()QueryBuilder 上调用它。

要在纯 Eloquent 中实现它,您可以使用以下内容:

$anuncios = Anuncios::select('user_id','estado')
    ->whereIn('user_id',$ids)
    ->where('estado','Activo')
    ->groupBy('user_id')
    ->count();

【讨论】:

    猜你喜欢
    • 2014-04-02
    • 1970-01-01
    • 1970-01-01
    • 2015-01-27
    • 2021-12-19
    • 1970-01-01
    • 2020-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多