1 回答
TA贡献1775条经验 获得超11个赞
我找不到减少查询数量的方法,但在我的本地测试中进行了后续工作。
public function foobar()
{
$popular = User::leftJoin('category_user as cu', 'users.id', '=', 'cu.user_id')
->join('categories as c', 'cu.category_id', '=', 'c.id')
->groupBy(['country', 'c.name'])
->get([
'users.country',
'c.name',
DB::raw('count(*) as total')
])
->groupBy('country')
->values()
->map(function (Collection $elt) {
return $elt->sortByDesc('total')->first();
}); // this one is same (to get popular category)
// this one for payments and number of users from that country
return User::leftJoin('payments as p', 'users.id', '=', 'p.user_id')
->groupBy('country')
->get(['country', DB::raw('sum(p.amount) as total'), DB::raw('count(distinct(users.id)) as userCount')])
->map(function ($col) use ($popular) { // merging two collections into one
$col->name = $popular->where('country', $col->country)->first()->name;
return $col;
});
}
它打印出这样的东西;
[
{
"country": "Canada",
"total": "1150",
"userCount": 2,
"name": "Housing"
},
{
"country": "Italy",
"total": "100",
"userCount": 1,
"name": "Kitchen"
},
{
"country": "USA",
"total": "200",
"userCount": 1,
"name": "Cooking"
}
]
- 1 回答
- 0 关注
- 133 浏览
添加回答
举报