gpt4 book ai didi

php - Laravel - 将关系添加到工厂创建的模型

转载 作者:行者123 更新时间:2023-12-04 15:38:44 25 4
gpt4 key购买 nike

我正在测试一个包含多对多关系的预加载关系。现在我在测试中有查询和附件。我想知道是否有办法将它们移入工厂,而不是将其作为测试的一部分。这将限制测试的大小,然后每次创建电影工厂时都可以创建和使用这些关系。

测试

public function grabFilmTest()
{
$film = factory(Film::class)->create();

$categories = Category::where('main-cat', 'Science')->where('sub-cat', 'Fiction')->first();
$languages = Languages::where('name', 'english')->first();

$film->categories()->attach($categories->id);
$film->languages()->attach($languages->id);

$response = $this->json('GET', '/film/' . $film->id)
->assertStatus(200);

$response
->assertExactJson([
'id' => $film->id,
'name' => $film->name,
'description' => $film->description,
'categories' => $film->categories->toArray(),
'languages' => $film->languages->toArray()

}

电影工厂

$factory->define(\App\Models\Film::class, function (Faker $faker){
return [
'id' => $faker->uuid,
'name' => $faker->text,
'description' => $faker->paragraph,
];
});

如果有人可以帮助我如何做到这一点或举个例子那就太好了 :D

最佳答案

你可以使用 factory statesfactory callbacks .

$factory->define(\App\Models\Film::class, function (Faker $faker){
return [
'id' => $faker->uuid,
'name' => $faker->text,
'description' => $faker->paragraph,
];
});
$factory->define(\App\Models\Category::class, function (Faker $faker){
return [
// Category fields
];
});
$factory->define(\App\Models\Language::class, function (Faker $faker){
return [
// Language fields
];
});
$factory->afterCreatingState(\App\Models\Film::class, 'with-category', function (\App\Models\Film $film) {
$category = factory(\App\Models\Category::class)->create();
$film->categories()->attach($category->id);
});
$factory->afterCreatingState(\App\Models\Film::class, 'with-language', function (\App\Models\Film $film) {
$language = factory(\App\Models\Language::class)->create();
$film->categories()->attach($language->id);
});

然后你可以像这样在测试中使用:

public function grabFilmTest()
{
$film = factory(Film::class)->create();
$filmWithCategory = factory(Film::class)->state('with-category')->create();
$filmWithLanguage = factory(Film::class)->state('with-language')->create();
$filmWithCategoryAnLanguage = factory(Film::class)->states(['with-category', 'with-language'])->create();
// ...
}

PS:我不建议使用现有数据。根据经验,我可以告诉你这会变得非常痛苦。

关于php - Laravel - 将关系添加到工厂创建的模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58846325/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com