php 在多对多关系 Laravel 中命名表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34897444/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
naming tables in many to many relationships laravel
提问by Pedram marandi
I concerned about auto naming tables in many-to-many Laravel relationship.
我关心多对多 Laravel 关系中的自动命名表。
for example:
例如:
Schema::create('feature_product', function (Blueprint $table) {}
when change the table name to:
将表名更改为:
Schema::create('product_feature', function (Blueprint $table) {}
I have an error in my relationship.
我的关系有错误。
What's the matter with product_feature
?
怎么回事product_feature
?
回答by patricus
Laravel's naming convention for pivot tables is snake_cased model names in alphabetical order separated by an underscore. So, if one model is Feature
, and the other model is Product
, the pivot table will be feature_product
.
Laravel 对数据透视表的命名约定是按字母顺序排列的snake_cased 模型名称,并用下划线分隔。因此,如果一个模型是Feature
,而另一个模型是Product
,则数据透视表将是feature_product
。
You are free to use any table name you want (such as product_feature
), but you will then need to specify the name of the pivot table in the relationship. This is done using the second parameter to the belongsToMany()
function.
您可以随意使用任何您想要的表名(例如product_feature
),但是您需要在关系中指定数据透视表的名称。这是使用belongsToMany()
函数的第二个参数完成的。
// 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');
}
You can read more about many to many relationships in the docs.