gpt4 book ai didi

php - Laravel Faker 工厂关系

转载 作者:行者123 更新时间:2023-12-01 23:27:47 25 4
gpt4 key购买 nike

我有两个工厂,一个负责品类,另一个负责产品。当我经营工厂时,我想为每个生成的类别创建 x 数量的产品。我将如何编写代码来生成此产品?

类别的定义是这样写的:

return [
'name' => $this->faker->word,
'slug' => Str::slug($this->faker->unique()->word, '-'),
];

产品的定义是这样写的:

return [
'category_id' => 1, //instead of 1 the category id used i want to be random
'name' => $this->faker->word,
'slug' => Str::slug($this->faker->unique()->word, '-'),
'description' => $this->faker->paragraph,
'price' => $this->faker->randomFloat(2, 0, 10000),
'is_visible' => 1,
'is_featured' => 1
];

如您所见,我对 category_id 进行了硬编码,我不太确定如何让它自动生成并为每个存在的类别创建产品。我有这样写的类别的工厂,以创建 10 个项目

Category::factory()
->count(10)
->create();

我尝试过尝试和错误,认为它会起作用,但我得到一个错误,即 category_id cannot be null

Product::factory()
->has(Category::factory()->count(2))
->count(20)
->create();

最佳答案

    $factory->define(Product::class, function (Faker $faker) {
return [
'category_id' => factory(Category::class), //instead of 1 the category id used i want to be random
'name' => $this->faker->word,
'slug' => Str::slug($this->faker->unique()->word, '-'),
'description' => $this->faker->paragraph,
'price' => $this->faker->randomFloat(2, 0, 10000),
'is_visible' => 1,
'is_featured' => 1
];
});

通过将属性设置为 factory() 的实例,Laravel 也会懒惰地创建该模型并自动关联它

关于php - Laravel Faker 工厂关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66927714/

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