我有一个名为item
的表,它与一个名为source
的表具有belongsTo关系。我想按源对所有项进行分组,最后我想要一个数组,该数组以source->name
作为键,以相关项的数量作为值。
这是我到目前为止所得到的:
Item::where('type', '=', Item::TYPE_POST)
->with('source')
->select('source_id', DB::raw('count(*) as total'))
->groupBy('source_id')
->pluck('total', 'source_id')
->all();
array:1 [
89 => 149
]
这给出了我想要的结构,但是条目不是按source->name
分组的,而是按source_id
分组的,这是Item
表中的一个字段。有没有办法让数组中的键成为相关表中的一个字段?
发布于 2019-03-26 06:52:54
我还没有试过这些,但无论如何它应该会让你更亲近
使用集合
Item::where('type', '=', Item::TYPE_POST)
->with('source.name')
->get()
->mapWithKeys(function ($item) {
return [$item->service->name => $item];
})
->map(function ($items, $name) {
return [
$name => $items->count()
];
});
使用查询
DB::table('items')
->selectRaw('sources.name as name, count(*.items) as count')
->join('sources', 'sources.id', 'items.source_id')
->where('type', '=', Item::TYPE_POST)
->groupBy('sources.id')
->get()
->pluck('count', 'name')
https://stackoverflow.com/questions/55345927
复制相似问题