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

如何用Laravel Eloquent统计按供应商所属社区分组的采购量及对应部门名

Laravel Eloquent 分组统计采购数量解决方案

你之前的写法统计的是社区下有采购记录的供应商个数,并非采购总数量,和你原生SQL的统计逻辑不一致,所以结果有误。

前置准备

你需要先在Supplier模型中补充缺失的关联关系:

// 关联所属社区
public function community()
{
    return $this->belongsTo(Community::class, 'community_id');
}

// 关联所属部门(如果部门字段在suppliers表就加这个;如果部门字段在communities表,不需要加这个,直接在Community模型中加department关联即可)
public function department()
{
    return $this->belongsTo(Department::class, 'department_id');
}

方案1:完全对齐原生SQL逻辑(按供应商分组统计)

和你给出的原生SQL逻辑完全一致,统计每个供应商的采购总数量,同时带出所属社区、部门名称:

$purchases = Supplier::query()
    ->selectRaw('count(purchases.id) as total, suppliers.id')
    ->join('purchases', 'suppliers.id', '=', 'purchases.supplier_id')
    ->with(['community:id,name', 'department:id,name'])
    ->groupBy('suppliers.id')
    ->orderByDesc('total')
    ->get();

遍历取值方式:

  • 采购数量:$item->total
  • 社区名称:$item->community->name
  • 部门名称:$item->department->name

方案2:按社区+部门分组统计总采购量

如果需要合并同一个社区同一部门下所有供应商的采购量,用以下写法:

$purchases = Supplier::query()
    ->selectRaw('count(purchases.id) as total, communities.name as CommunityName, departments.name as Department')
    ->join('purchases', 'suppliers.id', '=', 'purchases.supplier_id')
    ->join('communities', 'suppliers.community_id', '=', 'communities.id')
    // 如果部门字段在communities表,上面的关联条件改为 communities.department_id = departments.id
    ->join('departments', 'suppliers.department_id', '=', 'departments.id')
    ->groupBy('CommunityName', 'Department')
    ->orderByDesc('total')
    ->get();

内容的提问来源于stack exchange,提问作者FreddicMatters

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 12:15:08