mysql - Laravel - 雄辩的查询没有给出预期的结果
问题描述
在我的 Laravel-5.8 项目中,我有以下代码:
class Employee extends Model
{
protected $table = 'employees';
protected $fillable = [
'id',
'first_name',
'last_name',
];
public function leaverequest()
{
return $this->hasMany('App\Models\Hr\Goal');
}
}
class Goal extends Model
{
protected $table = 'goals';
protected $primaryKey = 'id';
protected $fillable = [
'id',
'employee_id',
'is_published',
'company_id',
];
public function employee()
{
return $this->belongsTo('App\Models\Hr\Employee', 'employee_id');
}
}
我想统计发布目标的员工人数,groupbyemployee_id
为is_published
1。
$testing = Goal::where('is_published', 1)
->where('company_id', $userCompany)
->groupBy('employee_id')
->count();
从表中我有四 (4) 行但相同employee_id
,我希望得到 1 但我得到 4?
dd($testing) 给我 4
我如何实现这一目标?
谢谢
解决方案
我认为你需要的是count
与distinct
查询是这样的;
select count(distinct employee_id) as total
from goals
where is_published = 1 and company_id = 1;
雄辩的方式;
$testing = Goal::where('is_published', 1)
->where('company_id', $userCompany)
->first([
DB::raw('count(distinct employee_id) as total')
])
->total;
推荐阅读
- html - 锚点无法以某种方式点击
- sdk - 使用 Rasbian 从 dji 矩阵 210 RTK 获取遥测数据到 Raspberry pi
- css - 如何使用css减少wordpress中的页脚高度?
- java - 使用 Jersey 2.29 注入带有自定义注释的方法参数
- asp.net - 如何创建包含`的javascript包
- xaml - 如何在资源字典中的 DataTemplate 中绑定命令?
- python - 无衬线竖立 mu
- reactjs - 如何从组件获取状态到导航选项?
- excel - 使用 debug.print 时,有没有办法让即时窗口显示实际选项卡而不是 4 个空格
- python - 如何从 csv 文件中删除所有点?