繁体   English   中英

如何将sum()与join和group by语句一起使用

[英]How to use sum() with join and group by statement

我想按货币合计金额

我在SQL中这样

select sum(total),currencies.currency_symbol from invoices
join(currencies)
where(invoices.currency_id = currencies.id)
group by(currency_id)

我这样在拉拉维(Laravel)试过

$sum = Invoice::sum('total')
              ->select('currency_symbol')
              ->join('currencies','invoices.currency_id','=','currencies.id')
              ->groupBy('currency_id');
return response()->json($sum);

但这会引发错误

Symfony \\ Component \\ Debug \\ Exception \\ FatalThrowableError:在字符串上调用成员函数select()

请给我解决方案

我认为您必须使用selectRaw,因为sum和select的组合我认为不会起作用,因此可以使用两者之一。 您可以尝试如下操作:

$sum = Invoice::selectRaw('currency_symbol, sum(total) as sum')
              ->join('currencies','invoices.currency_id','=','currencies.id')
              ->groupBy('currency_id');
return response()->json($sum);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM