分组后计数错误

时间:2019-02-03 22:02:36

标签: laravel builder

具有包含walletsservices的表

服务

id和名称

钱包

id service_id余额

$statistic = Wallets::leftJoin('service', 'service.id', '=', 'wallets.service_id')->select('name as label', 'balance as value')->where('balance', '>', 0)->whereYear('wallets.updated_at', $now->year)->whereMonth('wallets.updated_at', $now->month)->get();

并获得结果

[{"label":"Service1","value":0.0711679},
 {"label":"Service1","value":0.015},
 {"label":"Service2","value":0.065572},
 {"label":"Service2","value":0.02},
 {"label":"Service3","value":0.0206064},
 {"label":"Service2","value":0.04399}]

但在->groupBy('label'):之后

[{"label":"Service1","value":0.0711679},
{"label":"Service2","value":0.065572}
{"label":"Service3","value":0.0206064}]

仅获取第一个结果

1 个答案:

答案 0 :(得分:0)

<?php 

// If you are referring count as total balance then you can do this
$statistic = Wallets::leftJoin('service', 'service.id', '=', 'wallets.service_id')
->where('balance', '>', 0)
->whereYear('wallets.updated_at', $now->year)
->whereMonth('wallets.updated_at', $now->month)
->select(
    \DB::raw('name as label'), 
    \DB::raw('SUM(balance) as value')
)
->groupBy('name')
->get();

// If you are referring count as total entries for each label then you can do this
$statistic = Wallets::leftJoin('service', 'service.id', '=', 'wallets.service_id')
->where('balance', '>', 0)
->whereYear('wallets.updated_at', $now->year)
->whereMonth('wallets.updated_at', $now->month)
->select(
    \DB::raw('name as label'), 
    \DB::raw('balance as value'),
    \DB::raw('count(*) as aggregate')
)
->groupBy('name')
->get();