问题描述
我担心多对多Laravel关系中的自动命名表.
I concerned about auto naming tables in many-to-many Laravel relationship.
例如:
Schema::create('feature_product', function (Blueprint $table) {
将表名称更改为:
Schema::create('product_feature', function (Blueprint $table) {
我的恋爱关系有误.
product_feature
有什么问题?
推荐答案
Laravel对数据透视表的命名约定是使用下划线分隔的按字母顺序排列的snake_cased模型名称.因此,如果一个模型为Feature
,而另一个模型为Product
,则数据透视表将为feature_product
.
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
.
您可以随意使用所需的任何表名(例如product_feature
),但随后需要在关系中指定数据透视表的名称.这是通过belongsToMany()
函数的第二个参数完成的.
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.
// 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');
}
您可以阅读有关文档中很多关系的更多信息.
这篇关于在多对多关系中命名表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!