Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 958
AndHeiberg Avatar asked Feb 02 '13 20:02

AndHeiberg


2 Answers

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');
like image 135
Beau Avatar answered Oct 21 '22 01:10

Beau


Laravel seed files are regular PHP scripts (except they need to return an array). You can query the database in seed files (using Eloquent, Fluent builder or even PDO).

One way to tackle the many-to-many problem is to deliberately name your seed files so that the pivot table is populated last... For example, you could prepend a numeric value to the file name (i.e. 1_authors.php, 2_books.php, 3_authors_books.php etc.). Artisan sorts the filenames alphabetically before executing them.

I have posted a small tutorial on Laravel 4 database seeding - this should get you going. Additionally, you may consult the official doc on seeding.

like image 40
Max Ehsan Avatar answered Oct 21 '22 03:10

Max Ehsan