我在從兩個表中獲取某個字段的SUM時出現問題。Laravel 5.4來自兩個不同表的查詢生成器SUM()
因此,要開始的東西,這是我的查詢。
//Getting of Cost of Goods Sold (Menus)
$totalMenuCost = DB::raw('(SUM(orders.qty * orders.cost)) as cost');
$yearMenuSold = DB::raw('YEAR(orders.created_at) as year');
$menuscost = DB::table('orders')
->where('status', 'served')
->select($totalMenuCost, $yearMenuSold);
//Getting of Cost of Goods Sold (Items)
$totalItemCost = DB::raw('(SUM(purchases.qty * purchases.cost)) as cost');
$yearItemSold = DB::raw('YEAR(purchases.created_at) as year');
$itemcost = DB::table('purchases')
->where('status', 'served')
->union($menuscost)
->select($totalItemCost, $yearItemSold)
->get();
而且當我試着做return $itemcost
。它返回兩行:
[
{
cost: "792.00",
year: 2017
},
{
cost: "1700.00",
year: 2017
}
]
我試圖讓它返回一行而擁有它補充說,像這樣:
[
{
cost: "2492.00", // that's 1,700 + 792
year: 2017
}
]
你的工會應該在' - > get()'之前,嘗試使用group by –
@SagarGautam我切換了'select'和'union'。所以'union'就在' - > get()'之前,並且在'union'之前加上' - > groupBy('cost')'。但它有相同的輸出。 –
是的,根據你的要求使用' - > groupBy()',在這裏你可以按年分組來獲得你的輸出 –