首页 > 解决方案 > 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_idis_published1。

$testing = Goal::where('is_published', 1)
       ->where('company_id', $userCompany)
       ->groupBy('employee_id')
       ->count();

从表中我有四 (4) 行但相同employee_id,我希望得到 1 但我得到 4?

dd($testing) 给我 4

我如何实现这一目标?

谢谢

标签: mysqllaravel

解决方案


我认为你需要的是countdistinct

查询是这样的;

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;

推荐阅读