Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is a pivot table created by Laravel?

In Laravel 4, when working with many-to-many relationships as described in the 4.2 docs, how can I actually get Laravel to create the pivot table for me?

Do I need to add something in my migrations for the two models that are involved? Do I need to manually create a migration for the pivot table? Or how does Laravel know to create the pivot table?

All I've done so far is add the belongsToMany information to the two respective models, i.e.

class User extends Eloquent  {     public function roles()     {          return $this->belongsToMany('Role');      }  } 

However, that does not trigger creation of the pivot table. What step am I missing?

like image 855
Ben Avatar asked Apr 04 '13 21:04

Ben


People also ask

What is a pivot table in Laravel?

Definition of Laravel Pivot Table. A pivot table is defined as the set of values arranged in a table form where every distinct value of the concerned table can be accessed in the form of a spreadsheet, database, and so on. It is available in one or multiple discrete functionalities.

What is pivot table in Laravel 8?

What is a pivot table? A pivot table is used to connect relationships between two tables. Laravel provides a Many To Many relationship where you can use a pivot table.

How do you 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 .


2 Answers

It appears as though the pivot table does need to be created manually (i.e. Laravel does not do this automatically). Here's how to do it:

1.) Create a new migration, using singular table names in alphabetical order (default):

php artisan make:migration create_alpha_beta_table --create --table=alpha_beta 

2.) Inside the newly created migration, change the up function to:

public function up() {     Schema::create('alpha_beta', function(Blueprint $table)     {         $table->increments('id');         $table->integer('alpha_id');         $table->integer('beta_id');     }); } 

3.) Add the foreign key constraints, if desired. (I haven't gotten to that bit, yet).


Now to seed, say, the alpha table, using keys from beta, you can do the following in your AlphaTableSeeder:

public function run() {     DB::table('alpha')->delete();      Alpha::create( array(          'all'           =>  'all',         'your'          =>  'your',         'stuff'         =>  'stuff',     ) )->beta()->attach( $idOfYourBeta ); } 
like image 155
Ben Avatar answered Nov 09 '22 20:11

Ben


I use Jeffrey Way's Laravel-4-Generators or Laravel-5-Generators-Extended.

then you can just use this artisan command:

php artisan generate:pivot table_one table_two 
like image 31
user3260759 Avatar answered Nov 09 '22 18:11

user3260759