Laravel使用withCount()获取计数并在其上添加where子句

nzrxty8p  于 2023-10-22  发布在  其他
关注(0)|答案(1)|浏览(143)

我有一个像下面这样的查询,以获得用户关系上的打孔计数,然后想添加where子句来检查计数是否大于3,或者只获得打孔计数大于3的用户。

$repeatedlyLatemark = User::withCount(['punches'=> fn($q)=> $q
                ->where('is_latemark', '1')
                ->whereDate('punch_date', '>=', Carbon::today()->startOfMonth()->toDateString())
                ->whereDate('punch_date', '<=', Carbon::today()->endOfMonth()->toDateString())
            ])
            ->having('punches_count', '>', '3')
            ->when(!$is_admin, fn($q)=> $q->where('department_id', $authUser->department_id) )
            ->when($ward, fn($q)=> $q->where('ward_id', $ward))
            ->count();
ddrv8njm

ddrv8njm1#

注意:使用整数,而不是字符串'3'

$repeatedlyLatemark = User::withCount(['punches'=> fn($q)=> $q
            ->where('is_latemark', '1')
            ->whereDate('punch_date', '>=', Carbon::today()->startOfMonth()->toDateString())
            ->whereDate('punch_date', '<=', Carbon::today()->endOfMonth()->toDateString())
        ])
        ->having('punches_count', '>', 3)  // Note: Use integer, not string '3'
        ->when(!$is_admin, fn($q)=> $q->where('department_id', $authUser->department_id) )
        ->when($ward, fn($q)=> $q->where('ward_id', $ward))
        ->count();

相关问题