我在运行phpunit测试时遇到此错误:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'profile_id' cannot be null (SQL: insert into `comments` (`description`, `status`, `profile_id`, `project_id`, `updated_at`, `created_at`) values (Awesome Comment, active, , 21, 2016-01-29 00:05:21, 2016-01-29 00:05:21))
正如您所看到的那样,它为profile_id发送了一个空ID,我在创建注释之前创建了配置文件。这是我的测试代码:
public function testProjectCommentCreation()
{
$category = factory(\App\Category::class)->create();
$category->projects()->save(factory(\App\Project::class)->make());
$profile = factory(\App\Profile::class)->make([
'name' => 'John',
'last_name' => 'Snow',
'skills' => 'php'
]);
$category->projects[0]->comments()->save(factory(\App\Comment::class)->make([
'description'=>'Awesome Comment',
'status'=>'active',
'profile_id'=>$profile->id
]));
$this->post(route('api.projects.comments.store', ["projects" => $category->projects[0]->id]), $category->projects[0]->comments->jsonSerialize(), $this->jsonHeaders)
->seeInDatabase('comments', ['project_id' => $category->projects[0]->id])
->assertResponseOk();
}
一个项目属于一个类别,一个注释属于一个项目和一个配置文件,所以我需要发送外键值profile_id和project_id,问题是我不知道如何检索配置文件的id我创造了。
这些是我使用的工厂:
$factory->define(App\Profile::class, function (Faker\Generator $faker) {
return [
'name' => $faker->name,
'last_name' => $faker->name,
'status' => 'active',
'avatar' => str_random(10),
'skills'=> str_random(10),
'notifications'=>'on'
];
});
$factory->define(App\Comment::class, function (Faker\Generator $faker) {
return [
'description' => str_random(10),
'status' => 'active',
'profile_id' => 1,
'project_id' => 1
];});
$factory->define(App\Category::class, function (Faker\Generator $faker) {
return [
'description' => str_random(10),
'status' => 'active'
];});
$factory->define(App\Project::class, function (Faker\Generator $faker) {
return [
'description' => str_random(10),
'status' => 'active',
'privacy' => 'false'
];});
我已经测试了每种类型对象的构造并且它正在工作,我失败的是创建一个注释,因为我需要首先创建一个配置文件并检索id并且出于某种原因使用$ profile-&gt ; id正在拉空
答案 0 :(得分:2)
问题是,在使用make()
时,您的个人资料未保存到数据库中。
为了能够使用/分配来自profile_id
的外键$profile
,您需要create()
工厂模型,而不仅仅是make()
。< / p>
$profile = factory(\App\Profile::class)->create([
'name' => 'John',
'last_name' => 'Snow',
'skills' => 'php'
]);
这应该可以解决问题。