首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在使用并集时如何求两个不同表的和

在使用并集时如何求两个不同表的和
EN

Stack Overflow用户
提问于 2021-07-07 17:47:36
回答 1查看 41关注 0票数 0

我的代码如下所示

代码语言:javascript
复制
 $docManual = DB::table('document_manuals')
                    ->whereYear('document_manuals.created_at', $monthYear)
                    ->whereMonth('document_manuals.created_at', '=', $monthly)
                    ->select('document_manuals.format_type', DB::raw('count(*) as total'))
                    ->groupBy('document_manuals.format_type');
                    

                $format = DB::table('documents')
                    ->whereYear('documents.created_at', $monthYear)
                    ->whereMonth('documents.created_at', '=', $monthly)
                    ->select('.documents.format_type', DB::raw('count(*) as total'))
                    ->groupBy('documents.format_type')
                    ->unionAll($docManual)
                    ->get();

输出

代码语言:javascript
复制
Illuminate\Support\Collection {#1676 ▼
  #items: array:4 [▼
    0 => {#1679 ▼
      +"format_type": "pdf"
      +"total": 1
    }
    1 => {#1682 ▼
      +"format_type": "ppt"
      +"total": 1
    }
    2 => {#1678 ▼
      +"format_type": "doc"
      +"total": 1
    }
    3 => {#1684 ▼
      +"format_type": "pdf"
      +"total": 2
    }
  ]
}

我想让输出看起来像这样

代码语言:javascript
复制
Illuminate\Support\Collection {#1676 ▼
  #items: array:4 [▼
    0 => {#1679 ▼
      +"format_type": "pdf"
      +"total": 3
    }
    1 => {#1682 ▼
      +"format_type": "ppt"
      +"total": 1
    }
    2 => {#1678 ▼
      +"format_type": "doc"
      +"total": 1
    }
  ]
}

问题是如何使用UNION将两个表的项合并求和?为了更清楚,我有两个表,数据是:

代码语言:javascript
复制
first table : document_manuals
pdf : 1

second table : documents
pdf : 2
ppt : 1
doc : 1

有人知道如何组合它们,使输出看起来像我想要的那样吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-07-07 18:23:19

代码语言:javascript
复制
        $data = collect([
            ['format_type' => 'pdf', 'total' => 1],
            ['format_type' => 'ppt', 'total' => 1],
            ['format_type' => 'doc', 'total' => 1],
            ['format_type' => 'pdf', 'total' => 2],
        ]);
        $result = collect([]);
        $data->groupBy('format_type')->map(function ($item, $key) use ($result) {
            $result->push((object)['format_type' => $key, 'total' => $item->sum('total')]);
        });
        dd($result->toArray());
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68283690

复制
相关文章

相似问题

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