首页 > 解决方案 > Laravel 选择查询

问题描述

我为以下选择语句构建查询

SELECT empname, COUNT(empstatus) 
FROM empattens 
WHERE empstatus='Present' 
  AND id=1;

我使用的代码如下

Empatten::where('id', $id)
        ->where('empstatus', '=', 'Present')
        ->get()
        ->count('empstatus');

我只收到count(empstatus),但我empname也需要,

标签: phpmysqllaraveleloquent

解决方案


您可以使用该select()方法指定要选择的字段,然后将其与DB::raw()选择您的COUNT().

Empatten::select('empname', \DB::raw("COUNT(*) AS count"))
        ->where('id', $id)
        ->where('empstatus', '=', 'Present')
        ->get();

但这不一定是有效的 SQL,因为您在选择列时使用聚合函数(在本例中COUNT()为 ,但其他示例为MIN()MAX()、 )。您应该为选择列表中不属于聚合语句的列AVG()指定 a 。GROUP BY我们可以通过使用该groupBy()方法来做到这一点 - 结果不应该改变,因为您正在寻找一个特定的 ID。

Empatten::select('empname', \DB::raw("COUNT(*) AS count"))
        ->where('id', $id)
        ->where('empstatus', '=', 'Present')
        ->groupBy('empname')
        ->get();

推荐阅读