You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel Eloquent关联查询:按branch_code统计激活员工数

问题排查与修正

现有数据表结构

  • registrant表:id, branch_id, name
  • branch表:id, branch_code
  • employee表:id, registrant_id, name, status

需求

按branch_code分组,统计各分支下状态为Actived的员工数量

原代码问题

  1. 拼写错误:状态值写成了Actifed,正确应为Actived
  2. 多余过滤条件:whereRelation('registrant.branch', 'branch_code', $user->branch->branch_code)会把结果限定为当前用户所在分支,不符合"统计各分支"的需求,需移除
  3. 字段引用错误:select和groupBy中不能直接用registrant.branch.branch_code这种嵌套关联写法,得通过明确表名引用字段
  4. 关联关系需提前定义:确保模型已正确设置关联:
    • 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 19:45:56