How is a pivot table created by Laravel?

后端 未结 5 1485

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

5条回答
  •  死守一世寂寞
    2020-12-13 02:46

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

提交回复
热议问题