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

Laravel中如何对同一列不同两行的数值求和?代码仅返回最后一行值

问题原因及修复方案

核心问题点

  • 变量重复覆盖:你在第二层foreach中每次都直接给$selectProduct赋值,每一轮循环都会覆盖上一轮的计算结果,最终只能保留最后一次循环的求和值。
  • 循环变量名冲突:内外两层foreach都使用$key作为遍历变量,内层循环会覆盖外层的$key值,导致外层订单ID取值异常,进一步影响逻辑正确性。
  • 存在N+1查询性能问题:嵌套循环中每次都单独发起数据库查询,订单和关联商品数量较多时会产生大量无效数据库请求,性能损耗严重。

快速修复代码(直接解决当前报错)

public function index()
{
    
    $orders = Order_Ecommerces::orderBy('created_at', 'DESC')->get();
    // 初始化求和累加器
    $selectProduct = 0;
    // 外层循环变量改名,避免和内层冲突
    foreach ($orders as $order) {
        $totalpricePerOrder=DB::table('order_ecommerce_product')->where('order_ecommerce_id', '=', $order['id'])->get();
        // 内层循环变量改名
        foreach ($totalpricePerOrder as $orderProduct) {
            // 累加求和,而非直接覆盖赋值
            $selectProduct += DB::table('products')->where('id','=',$orderProduct->product_id)->sum('prezzo_al_pezzo');
        }
    }
    return view('ecommerce.orders', compact('orders','selectProduct'));
}

优化版本(解决性能问题)

不需要嵌套循环查库,单条SQL直接计算所有关联商品总价:

public function index()
{
    $orders = Order_Ecommerces::orderBy('created_at', 'DESC')->get();
    // 关联查询直接计算总和,仅发起1次数据库请求
    $selectProduct = DB::table('order_ecommerce_product')
        ->join('products', 'order_ecommerce_product.product_id', '=', 'products.id')
        ->sum('products.prezzo_al_pezzo');

    // 如果需要按订单维度分别存储每个订单的总价,可改用以下逻辑
    // $selectProduct = [];
    // foreach ($orders as $order) {
    //     $selectProduct[$order['id']] = DB::table('order_ecommerce_product')
    //         ->join('products', 'order_ecommerce_product.product_id', '=', 'products.id')
    //         ->where('order_ecommerce_product.order_ecommerce_id', $order['id'])
    //         ->sum('products.prezzo_al_pezzo');
    // }

    return view('ecommerce.orders', compact('orders','selectProduct'));
}

内容的提问来源于stack exchange,提问作者alessio scionti

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 06:39:03