我有两家工厂,一家生产类别,另一家生产产品。当我运行工厂时,我想为生成的每个类别创建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();发布于 2021-04-03 12:40:15
$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也会懒洋洋地创建该模型,并自动关联它
发布于 2021-04-03 12:43:48
我正在使用一种不同的语法,但我认为它会起作用/你可以改变它
在Category.php模型中
public function products() {
return $this->hasMany(Product::class);
}在seeder中
factory(App\Category::class, 10)->create()->each(function($c) {
$c->products()->save(factory(App\Product::class)->make());
}); // each Category will have 1 product发布于 2021-04-03 13:22:06
您只需要向category_id传递一个CategoryFactory。
return [
'category_id' => Category::factory(),
// ...
];您可以在此处阅读有关工厂的更多信息:https://laravel.com/docs/8.x/database-testing#defining-relationships-within-factories
https://stackoverflow.com/questions/66927714
复制相似问题