如何解决Laravel Faker 工厂关系
我有两个工厂,一个用于类别,另一个用于产品。当我运行工厂时,我想为每个生成的类别创建 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,'description' => $this->faker->paragraph,'price' => $this->faker->randomFloat(2,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,10000),'is_visible' => 1,'is_featured' => 1
];
});
通过将属性设置为 factory() 的实例,Laravel 也会懒惰地创建该模型并自动关联它
,我使用了一种不同的语法,但我认为它会起作用/你可以改变它
在您的 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
Laravel Database Testing Relationships
,您只需将 CategoryFactory
传递给 category_id
。
return [
'category_id' => Category::factory(),// ...
];
您可以在此处阅读有关工厂的更多信息:https://laravel.com/docs/8.x/database-testing#defining-relationships-within-factories
,这对我有用,因为我使用的是 laravel 8。
产品定义:
return [
'category_id' => Category::factory(),'name' => $this->faker->word,1000),'is_featured' => 1
];
播种机:
Product::factory()
->has(Category::factory())->count(50)
->create();
创建了 50 个类别和 50 个产品。为每个产品分配 1 个类别。
,如果您想为每个创建的类别创建多个产品,您可以执行以下操作:
// CategoryProductSeeder
$categories = Category::factory(50)->create();
$categories->each(function ($category) {
$categories->products()->saveMany(
Product::factory(10)->make()
);
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。