Laravel-雄辩的查询没有给出预期的结果

时间:2020-06-30 10:15:52

标签: 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');
    }
}

我想统计已发布目标和分组方式的员工人数,employee_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

我该如何实现?

谢谢

1 个答案:

答案 0 :(得分:0)

我认为您需要的是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;