Search code examples
databasemany-to-manylaravellaravel-4

Laravel 4: Working with relationships in seeds


Is there an easy way to manage many-to-many relationships in the new seeds feature of L4?

One way would be to make a seed for the pivot table, but I would be a lot of work.

Any thoughts on a good workflow for this sort of thing?


Solution

  • In the latest version of Laravel 4 you define the order that all the seeder scripts are run in the "run" method of the DatabaseSeeder class.

    public function run()
    {
        DB::statement('SET FOREIGN_KEY_CHECKS=0;');
    
        $this->call('PrimaryTableOneSeeder');
        $this->command->info('The first primary table has been seeded!');
    
        $this->call('PrimaryTableTwoSeeder');
        $this->command->info('The second primary table has been seeded!');
    
        $this->call('PivotTableSeeder');
        $this->command->info('The pivot table has been seeded!');
    
        DB::statement('SET FOREIGN_KEY_CHECKS=1;');
    }
    

    You'll notice that I disable the foreign key constraints before and after running all my seeding. This may be bad practice but it's the only way I can use the truncate function to re-set the id count for each table. If you follow the guide on inserting related models this practice may be unnecessary.

    class PrimaryTableOneSeeder extends Seeder {
    
    public function run()
    {
        DB::table('primaryone')->truncate();
        Primaryone::create(array(
            'field' => 'value',
            'created_at' => new DateTime,
            'updated_at' => new DateTime
        ));
    }
    

    To use mass assignment as I'm doing in my example and as the latest version of the documentation does, you'll need to specify either some guarded or fillable columns for the model. To do this simply add property to your model like this:

    class Primaryone extends Eloquent {
    
    protected $guarded = array('id');