vendredi 22 septembre 2017

Laravel Database Seeding- using Foreign Key

I am trying to use Laravel Database seeding to populate my tables. But I am not so sure how to do it properly. This is the code in my ModelFactory.

$factory->define(App\Course::class, function ($faker) {

return [
    'code' => $faker->word." ".$faker->word,
    'title' => $faker->sentence,
    'description' => $faker->paragraph,
    'year' => $faker->date,
    'created_by' => function(){
        return factory('App\User')->create()->id;
    },
    'university_id' => function(){
        return factory('App\University')->create()->id;
    },
    'department_id' => function(){
        return factory('App\Department')->create()->id;
    },
];

});

This creates a Course, but it also creates a new user, a new university, a new department.. New university creates another user, new department creates both a new user and a new university because of the following code:

$factory->define(App\University::class, function ($faker) {

return [
    'name' => $faker->word." University",
    'country' => $faker->country,
    'created_by' => function(){
        return factory('App\User')->create()->id;
    }
];

});

$factory->define(App\Department::class, function ($faker) {

return [
    'name' => $faker->word,
    'description' => $faker->paragraph,
    'created_by' => function(){
        return factory('App\User')->create()->id;
    },
    'university_id' => function(){
        return factory('App\University')->create()->id;
    }
];

});

What I want is this- I want to use an existing user, an existing university and an existing department to be assigned to each new course.

The following code only does it for the department. How can I do it for user and university as well?

factory('App\Department',20)->create()->each(function($department){factory('App\Course',1)->create(['department_id'=>$department->id]);});

Aucun commentaire:

Enregistrer un commentaire