首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >分组并统计相关模型

分组并统计相关模型
EN

Stack Overflow用户
提问于 2019-03-26 04:29:23
回答 1查看 30关注 0票数 0

我有一个名为item的表,它与一个名为source的表具有belongsTo关系。我想按源对所有项进行分组,最后我想要一个数组,该数组以source->name作为键,以相关项的数量作为值。

这是我到目前为止所得到的:

代码语言:javascript
复制
Item::where('type', '=', Item::TYPE_POST)
  ->with('source')
  ->select('source_id', DB::raw('count(*) as total'))
  ->groupBy('source_id')
  ->pluck('total', 'source_id')
  ->all();
代码语言:javascript
复制
array:1 [
  89 => 149
]

这给出了我想要的结构,但是条目不是按source->name分组的,而是按source_id分组的,这是Item表中的一个字段。有没有办法让数组中的键成为相关表中的一个字段?

EN

回答 1

Stack Overflow用户

发布于 2019-03-26 06:52:54

我还没有试过这些,但无论如何它应该会让你更亲近

使用集合

代码语言:javascript
复制
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()
        ];
    });

使用查询

代码语言:javascript
复制
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')
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55345927

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档