2016-11-08 63 views
1

我正在嘗試創建一個使用模型工廠的用戶,但我在關係中出現錯誤。在User型號中,我爲JobLevel型號創建了belongsTo關係levels。在ModelFactory.php我有以下代碼。使用Laravel模型工廠創建關係

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), 
    ]; 
}); 

然後我在我的測試班我使用的工廠如下。

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

      ... 
     } 

當我運行phpunit我收到以下錯誤

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)) 

回答

0

你能,用於測試目的試試這個?

$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(); 

     ... 
    } 

我不知道你可以嵌入這些工廠。

+0

仍然不能正常工作 –

+0

夠公平的,但是你仍然得到SQL錯誤信息? –

+0

是的,我仍然得到錯誤 –