【问题标题】:Laravel DB::raw() to take dynamic inputsLaravel DB::raw() 接受动态输入
【发布时间】: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 太陌生了,我没有想到,让我试试

标签: laravel eloquent


【解决方案1】:

您可以使用基本 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
注意:注意逗号在字符串中的位置,这可能会导致查询异常

【讨论】:

    猜你喜欢
    • 2015-10-06
    • 2016-07-29
    • 2018-10-24
    • 2019-01-10
    • 2015-03-26
    • 1970-01-01
    • 2019-08-20
    • 2014-12-05
    • 2017-11-17
    相关资源
    最近更新 更多