You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中如何在DB::raw()内动态拼接字段实现求和查询

你可以通过动态拼接SQL求和表达式的方式实现需求,同时注意做好字段校验避免SQL注入风险,修改后的代码如下:

// 新增可选参数 $additionalCostFields 用于传入需要叠加的动态字段列表
private function integrationsSpendBySupplier(array $suppliers, array $additionalCostFields = [])
{
    // 配置允许参与计算的额外字段白名单,避免SQL注入风险
    $allowedFields = ['shipping', 'tax', 'something_else', 'other_cost'];
    // 过滤出合法的额外字段
    $validAdditionalFields = array_filter($additionalCostFields, fn($field) => in_array($field, $allowedFields));

    // 构造求和表达式,固定保留price字段
    $sumColumns = ['price'];
    foreach ($validAdditionalFields as $field) {
        // 如果字段允许为NULL,可替换为 "COALESCE({$field}, 0)" 避免求和结果为NULL
        $sumColumns[] = $field;
    }
    $sumExpr = implode(' + ', $sumColumns);

    $totalBySupplier = DB::table('analytics')
        ->whereIn('source', $suppliers)
        ->select(
            'source',
            DB::raw("sum({$sumExpr}) 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
    ];
}

调用示例

  • 仅统计固定price字段:$this->integrationsSpendBySupplier($suppliers);
  • 叠加shipping和tax字段统计:$this->integrationsSpendBySupplier($suppliers, ['shipping', 'tax']);

如果你的额外字段允许为NULL,建议将拼接的字段替换为COALESCE(字段名, 0),避免NULL值参与运算导致总和为NULL的问题,对应拼接逻辑修改为:

$sumColumns[] = "COALESCE({$field}, 0)";

内容的提问来源于stack exchange,提问作者Riza Khan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 00:15:05