問題描述
我擔(dān)心多對多 Laravel 關(guān)系中的自動命名表.
I concerned about auto naming tables in many-to-many Laravel relationship.
例如:
Schema::create('feature_product', function (Blueprint $table) {}
當(dāng)表名改為:
Schema::create('product_feature', function (Blueprint $table) {}
我的關(guān)系有問題.
product_feature
有什么問題?
推薦答案
Laravel 對數(shù)據(jù)透視表的命名約定是用蛇形大小寫的模型名稱按字母順序用下劃線分隔.因此,如果一個模型是 Feature
,另一個模型是 Product
,那么數(shù)據(jù)透視表將是 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
),但是您需要在關(guān)系中指定數(shù)據(jù)透視表的名稱.這是使用 belongsToMany()
函數(shù)的第二個參數(shù)完成的.
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('AppFeature', 'product_feature');
}
// in Feature model
public function products()
{
return $this->belongsToMany('AppProduct', 'product_feature');
}
您可以在文檔中閱讀有關(guān)多對多關(guān)系的更多信息一>.
You can read more about many to many relationships in the docs.
這篇關(guān)于在多對多關(guān)系 Laravel 中命名表的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!