jeudi 28 avril 2016

laravel how to database seed with two different classes that have the same collection name?

I am trying to create a semi Single Table Inheritance using Eloquent (I am using MongoDB but that doesn't matter):

I have a class Person that has the collection people. The person class has a role attribute. One of the roles is 'athlete'.

Then, I created another class Athlete that extends Person. I have set up class like the following:

 class Athlete extends Person {
      protected $collection = 'people';

      public $role = 'athlete';
 }

When I do database seed to both generic person and athlete. Here is my model factory:

$factory->define(App\Modules\User\Models\User::class, function (Faker\Generator $faker) {
    $password = str_random(10);
    return [
        'name' => $faker->name,
        'email' => $faker->safeEmail,
        'password' => bcrypt($password),
        'password_raw' => $password,
        'remember_token' => str_random(10),
        'role' => 'admin'
    ];
});

$factory->define(App\Modules\Athletes\Models\Athlete::class, function (Faker\Generator $faker) {
    $password = str_random(10);
    $sports = ['Triathlon', 'Wrestling', 'Swimming', 'Archery', 'Rowing', 'Tennis', 'Road cycling', 'Diving', 'Boxing', 'Badminton'];
    return [
        'name' => $faker->name,
        'email' => $faker->safeEmail,
        'password' => bcrypt($password),
        'remember_token' => str_random(10),
        'sports' => $sports[$faker->biasedNumberBetween(0, 9)],
        'role' => 'athlete'
    ];
});

When I do php artisan db:seed the output shows that both seed classes UserDatabaseSeeder and AthleteDatabaseSeeder is seeded. However, when I test the database, it only shows 10 values from athlete seeder. Here are the seeders:

class AthleteDatabaseSeeder extends Seeder
{

    public function run()
    {
        Model::unguard();
        factory(Athlete::class, 10)->create();
        Model::reguard();
    }
}

class UserDatabaseSeeder extends Seeder {

    public function run() {
        Model::unguard();
        factory(User::class, 10)->create();
        Model::reguard();
    }
}

How can I make the seeder work?

Thank you!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire