gpt4 book ai didi

php - 来自两个不同表的 Laravel 5.4 Query Builder SUM()

转载 作者:行者123 更新时间:2023-11-29 03:20:48 25 4
gpt4 key购买 nike

我在从两个表中获取特定字段的 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
}
]

最佳答案

$itemcost =  DB::table('purchases')
->where('status', 'served')
->union($menuscost)
->select($totalItemCost, $yearItemSold)
->get();

在您的示例中,您只是从其他表($menuscost)中选择 $totalItemCost、$yearItemSold 和 union。

所以这不会将结果相加。

///////////尝试以这种格式更改您的查询

select column1,sum(column2) total
from
(
select column1,column2
from Table1
union all
select column1,column2
from Table2
) t
group by column1

希望这有帮助..如果需要更多帮助,请告诉我。

关于php - 来自两个不同表的 Laravel 5.4 Query Builder SUM(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45558483/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com