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

Laravel Eloquent多对多关系中如何自定义中间表名称?

解决Laravel多对多关联自定义中间表名称的问题

你需要在belongsToMany关联定义中显式指定中间表名称,仅在BrandSupplier模型中设置$table属性不足以覆盖Eloquent的默认中间表规则——关联建立时,Eloquent会优先使用默认命名逻辑生成表名,而非读取Pivot模型的表配置。

修改后的模型代码如下:

Supplier 模型

public function brands(){
    return $this->belongsToMany(Brand::class, 'brand_suppliers')->using(BrandSupplier::class);
}

Brand 模型

public function suppliers(){
    return $this->belongsToMany(Supplier::class, 'brand_suppliers')->using(BrandSupplier::class);
}

补充说明

  • belongsToMany的第二个参数就是自定义中间表的名称,传入你的实际表名brand_suppliers即可覆盖默认的brand_supplier。
  • BrandSupplier模型中的protected $table = 'brand_suppliers';仍需保留,当你需要直接操作中间表记录(比如BrandSupplier::create())时,这个配置会生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 09:52:31