php - Creating relations using Laravel model factories -
i trying create user using model factories having error relationships. in user
model, have created belongsto
relationship levels
model joblevel
. in modelfactory.php
have 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 in test class use factory follows.
/** @test */ public function login_a_user() { $user = factory(user::class)->create(); ... }
when run phpunit
following error
illuminate\database\queryexception: sqlstate[23000]: integrity constraint violation: 1452 cannot add or update child row: 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 `user` (`updated_at`, `created_at`) values (2016-11-08 12:01:14, 2016-11-08 12:01:14))
could you, testing purposes try this?
$factory->define(user::class, function (faker\generator $faker) { return [ 'firstname' => $faker->name, 'middlename' => $faker->name, 'lastname' => $faker->name, 'email' => $faker->email, 'job_level_id' => 1, 'password' => bcrypt(str_random(10)), 'remember_token' => str_random(10), ]; }); public function login_a_user() { $job = factory(joblevel::class)->create(); $user = factory(user::class)->create(); ... }
i not sure can embed factories.
Comments
Post a Comment