【发布时间】:2021-11-13 22:43:40
【问题描述】:
我有疑问从哪里获得供应商的价格总和。下面的查询工作正常。
private function integrationsSpendBySupplier(array $suppliers)
{
$totalBySupplier = DB::table('analytics')
->whereIn('source', $suppliers)->select(
'source',
DB::raw('sum(price) as total')
)
->groupBy('source')
->get();
return [
'title' => 'Spend per Supplier',
'rows' => 12,
'type' => 'bar',
'data' => [
'labels' => $totalBySupplier->map(fn ($supplier) => $supplier->source),
'datasets' => [
[
'label' => 'Total Spending',
'data' => $totalBySupplier->map(fn ($supplier) => $this->stringToFloat($supplier->total))
],
]
],
'hasToolTip' => true
];
}
但是,我还想向DB::raw() 调用添加更多项目,如下所示:
DB::raw('sum(price + shipping + tax + something_else) as total')
但这些值将是动态的,因此它可以是全部或没有额外参数(但价格将始终存在)。
有什么想法吗?
【问题讨论】:
-
您在哪里遇到问题?您可以使用一些基本的字符串操作,例如
DB::raw('sum(price'.($shouldIncludeShipping ? '+shipping':'')等等 -
是的...我对 PHP 太陌生了,我没有想到,让我试试