mardi 8 novembre 2016

Creating relations using Laravel model factories

I am trying to create a user using model factories but I am having an error with the relationships. In the User model, I have created a belongsTo relationship levels for the model JobLevel. In the ModelFactory.php I have the following code.

    use App\User;
use App\JobLevel;

$factory->define(JobLevel::class, function (Faker\Generator $faker) {
    return [
        'name' => $faker->word,
        'rank' => $faker->randomDigit,
    ];
});

$factory->define(User::class, function (Faker\Generator $faker) {
    return [
        'firstname' => $faker->name,
        'middlename' => $faker->name,
        'lastname' => $faker->name,
        'email' => $faker->email,
        'job_level_id' => factory(JobLevel::class)->create()->id,
        'password' => bcrypt(str_random(10)),
        'remember_token' => str_random(10),
    ];
});

Then I am in my test class I use the factory as follows.

   /** @test */
        public function login_a_user()
        {
            $user = factory(User::class)->create();

            ...
        }

When I run phpunit I get the following error

    Illuminate\Database\QueryException: SQLSTATE[23000]: Integrity 

    constraint violation: 1452 Cannot add or update a child row: a foreign key 

    constraint fails (`testing_db`.`user`, CONSTRAINT `fk_user_job_level1`

 FOREIGN KEY (`job_level_id`) REFERENCES `job_level` (`id`) ON DELETE NO 

ACTION ON UPDATE NO ACTION) (SQL: insert into `user` (`updated_at`, 

`created_at`) values (2016-11-08 12:01:14, 2016-11-08 12:01:14))



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire