我的代码如下所示
$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();输出
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
}
]
}我想让输出看起来像这样
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将两个表的项合并求和?为了更清楚,我有两个表,数据是:
first table : document_manuals
pdf : 1
second table : documents
pdf : 2
ppt : 1
doc : 1有人知道如何组合它们,使输出看起来像我想要的那样吗?
发布于 2021-07-07 18:23:19
$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());https://stackoverflow.com/questions/68283690
复制相似问题