Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

naming tables in many to many relationships laravel

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?

like image 337
Pedram marandi Avatar asked Jan 20 '16 10:01

Pedram marandi


People also ask

How do you name a table with many to many?

The ORM suggests pluralizing table names, using all lowercase names, and using underscores for many-to-many table names. So for your example, you'd have the following tables: clients, brokers, and brokers_clients (the ORM suggests alphabetically arranging table names for many-to-many tables).

How do I name a pivot table in laravel?

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 .


1 Answers

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.

like image 58
patricus Avatar answered Sep 20 '22 11:09

patricus