Laravel Eloquent关联查询:按branch_code统计激活员工数
问题排查与修正
现有数据表结构
- registrant表:
id,branch_id,name - branch表:
id,branch_code - employee表:
id,registrant_id,name,status
需求
按branch_code分组,统计各分支下状态为Actived的员工数量
原代码问题
- 拼写错误:状态值写成了
Actifed,正确应为Actived - 多余过滤条件:
whereRelation('registrant.branch', 'branch_code', $user->branch->branch_code)会把结果限定为当前用户所在分支,不符合"统计各分支"的需求,需移除 - 字段引用错误:
select和groupBy中不能直接用registrant.branch.branch_code这种嵌套关联写法,得通过明确表名引用字段 - 关联关系需提前定义:确保模型已正确设置关联:
Employee模型:public function registrant() { return $this->belongsTo(Registrant::class); }Registrant模型:public function branch() { return $this->belongsTo(Branch::class); }
修正后的代码
Employee::where('status', 'Actived') ->join('registrant', 'employee.registrant_id', '=', 'registrant.id') ->join('branch', 'registrant.branch_id', '=', 'branch.id') ->select(DB::raw('count(employee.id) as employee_count, branch.branch_code')) ->groupBy('branch.branch_code') ->get();
如果偏好关联查询写法(需确保模型关联正确):
Employee::where('status', 'Actived') ->join('registrant', 'employee.registrant_id', '=', 'registrant.id') ->join('branch', 'registrant.branch_id', '=', 'branch.id') ->select(DB::raw('count(employee.id) as employee_count, branch.branch_code')) ->groupBy('branch.branch_code') ->get();
补充说明
- 用
count(employee.id)比count(status)更准确,避免status为null时影响统计结果 - 若你实际需求是仅统计当前用户所在分支,可重新添加
where('branch.branch_code', $user->branch->branch_code)条件,但这会偏离"统计各分支"的原始需求
内容的提问来源于stack exchange,提问作者Bayustypryg
相关产品推荐
相关产品推荐

