Laravel DB::raw() 获取动态输入

Laravel DB::raw() to take dynamic inputs

我想知道我从哪里得到供应商的价格总和。以下查询工作正常。

    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')

但这些值将是动态的,因此它可能是全部或 none 附加参数(但价格将始终存在)。

有什么想法吗?

您可以使用基本 PHP 字符串构建 SUM() 字符串并将该字符串应用于查询。

例如

$price = ''; 
if (priceRequired())
  $price = "price ";     

$shipping = '';
if (requiresShipping())
  $shipping  = ", shipping";

// $shipping = requiresShipping() ? ", shipping" : ""; if you're familiar with this syntax 

... 

DB::raw("sum($price $shipping ...etc) as total");

因此,根据上述条件,最终字符串应该类似于 price, shipping, taxprice
注意:注意逗号在字符串中的位置,这可能会导致查询异常