[英]Laravel Faker Factory Relationship
我有两个工厂,一个用于类别,另一个用于产品。 当我运行工厂时,我想为生成的每个类别创建 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 也会懒惰地创建 model 并自动关联它
我正在使用一种不同的语法,但我认为它会起作用/你可以改变它
在您的Category.php
中。php model
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
您只需将CategoryFactory
传递给category_id
。
return [
'category_id' => Category::factory(),
// ...
];
您可以在此处阅读有关工厂的更多信息: https://laravel.com/docs/8.x/database-testing#defining-relationships-within-factories
如果要为每个创建的类别创建多个产品,可以执行以下操作:
// CategoryProductSeeder
$categories = Category::factory(50)->create();
$categories->each(function ($category) {
$categories->products()->saveMany(
Product::factory(10)->make()
);
});
这对我有用,因为我使用的是 laravel 8。
产品定义:
return [
'category_id' => Category::factory(),
'name' => $this->faker->word,
'slug' => Str::slug($this->faker->unique()->word, '-'),
'description' => $this->faker->paragraph,
'price' => $this->faker->randomFloat(2, 0, 1000),
'is_visible' => 1,
'is_featured' => 1
];
播种机:
Product::factory()
->has(Category::factory())->count(50)
->create();
创建了 50 个类别和 50 个产品。 分配给每个产品的 1 个类别。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.