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

Laravel Eloquent中对嵌套关联属性值进行计数与分组的实现问题

最优方案:数据库层面直接统计(效率最高,避免全量加载数据)

如果你要统计所有客户的性别分布:

$genderCounts = \DB::table('customers')
    ->join('genders', 'customers.gender', '=', 'genders.id')
    ->selectRaw('genders.name as gender_name, count(customers.id) as customer_count')
    ->groupBy('gender_name')
    ->pluck('customer_count', 'gender_name');

// 直接输出你需要的格式
echo $genderCounts->map(fn($count, $name) => "{$name} = {$count}")->join(',');

如果你要统计有下单记录的客户的性别分布(自动去重同一个用户的多笔订单):

$orderGenderCounts = \DB::table('orders')
    ->join('customers', 'orders.customer_id', '=', 'customers.id')
    ->join('genders', 'customers.gender', '=', 'genders.id')
    ->selectRaw('genders.name as gender_name, count(DISTINCT customers.id) as customer_count')
    ->groupBy('gender_name')
    ->pluck('customer_count', 'gender_name');

原有写法的问题&修正方案

你原来的代码仅做了集合分组,没有做数量统计,同时分组的关联路径写错了,修正后写法如下:

注意:该方案会全量加载所有订单关联数据,仅适合小数据量场景,不推荐生产环境使用

$orders = Order::with('customer.gender')
    ->get()
    // 嵌套关联的分组路径要写全 customer.gender.name
    ->groupBy('customer.gender.name')
    // 统计每个分组的数量
    ->map(fn($group) => $group->count());

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 01:09:04