naming tables in many to many relationships laravel

≡放荡痞女 提交于 2019-12-18 03:02:00

问题


I concerned about auto naming tables in many-to-many Laravel relationship.

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?


回答1:


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.

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');
}

You can read more about many to many relationships in the docs.



来源:https://stackoverflow.com/questions/34897444/naming-tables-in-many-to-many-relationships-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!