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

Laravel中如何通过关联四张表正确更新指定列数据

问题原因&解决方法

核心问题点

  • 表名前缀不匹配:你提供的实际数据表名均带default_前缀,但代码中使用的表名未携带该前缀,若你未在数据库配置中配置表前缀,会导致表匹配失败。
  • 多表关联更新逻辑错误:Laravel查询构造器的update方法默认作用于DB::table()指定的主表,你当前主表为商品表,要更新的是关联的里程间隙表字段,部分版本下该写法无法生效。

修正后代码

$qty = 1;
// 直接将需要更新的表作为主查询表
$updatedNum = DB::table('default_products_product_mileage_gap')
    ->join(
        'default_products_products_mileage_gaps',
        'default_products_product_mileage_gap.id',
        '=',
        'default_products_products_mileage_gaps.related_id'
    )
    ->join(
        'default_products_products',
        'default_products_products_mileage_gaps.entry_id',
        '=',
        'default_products_products.id'
    )
    ->join(
        'default_products_mileage_gap',
        'default_products_product_mileage_gap.mileage_gap_id',
        '=',
        'default_products_mileage_gap.id'
    )
    ->where('default_products_product_mileage_gap.number_of_products', '>', 0)
    ->where('default_products_mileage_gap.name', '=', $mileage_name)
    ->where('default_products_products.id', '=', $id)
    ->update([
        'number_of_products_sold' => $qty
    ]);

// 可打印返回值确认更新行数,返回0代表没有符合条件的待更新记录
// var_dump($updatedNum);

补充说明

  • 如果你已经在config/database.php中配置了数据库表前缀为default_,可以去掉代码中所有表名的default_前缀,仅将主表替换为products_product_mileage_gap即可。
  • 若运行后返回更新行数为0,可将update方法替换为->get()打印匹配到的数据集,排查where条件是否匹配到对应记录。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 12:06:02