在多对多关系中命名表
2022-08-30 10:59:58
我担心多对多Laravel关系中的自动命名表。
例如:
Schema::create('feature_product', function (Blueprint $table) {}
将表名更改为:
Schema::create('product_feature', function (Blueprint $table) {}
我的关系中有一个错误。
这是怎么回事?product_feature
我担心多对多Laravel关系中的自动命名表。
例如:
Schema::create('feature_product', function (Blueprint $table) {}
将表名更改为:
Schema::create('product_feature', function (Blueprint $table) {}
我的关系中有一个错误。
这是怎么回事?product_feature
Laravel的数据透视表命名约定是按字母顺序snake_cased模型名称,并用下划线分隔。因此,如果一个模型是 ,而另一个模型是 ,则数据透视表将为 。FeatureProductfeature_product
您可以自由使用所需的任何表名称(例如 ),但随后需要在关系中指定数据透视表的名称。这是使用函数的第二个参数完成的。product_featurebelongsToMany()
// in Product model
public function features()
{
return $this->belongsToMany('App\Feature', 'product_feature');
}
// in Feature model
public function products()
{
return $this->belongsToMany('App\Product', 'product_feature');
}
您可以在文档中阅读有关许多对许多关系的更多信息。