Php 拉维尔造假者工厂关系

Php 拉维尔造假者工厂关系,php,laravel,eloquent,factory,Php,Laravel,Eloquent,Factory,我有两个工厂,一个是分类工厂,另一个是产品工厂。当我运行工厂时,我想为生成的每个类别创建x个产品。如何编写此产品的代码 类别的定义如下所示: return [ 'name' => $this->faker->word, 'slug' => Str::slug($this->faker->unique()->word, '-'), ]; 产品的定义是这样写的: return [

我有两个工厂,一个是分类工厂,另一个是产品工厂。当我运行工厂时,我想为生成的每个类别创建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
            ];
正如您所看到的,我硬编码了
类别id
,我不太确定如何让它根据存在的类别自动生成和创建产品。我有这样写的类别的工厂,创建10个项目

Category::factory()
                ->count(10)
                ->create();
我尝试了这个尝试和错误,认为它会工作,但我得到了一个错误,
category\u id不能为null

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

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

我使用的是不同的语法,但我认为它会起作用/您可以更改它

在您的
Category.php
模型中

public function products() {
    return $this->hasMany(Product::class);
}
播种机中

factory(App\Category::class, 10)->create()->each(function($c) {
    $c->products()->save(factory(App\Product::class)->make());
}); // each Category will have 1 product

这是我使用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个类别。

您只需将
类别工厂
传递给
类别id

返回[
'category_id'=>category::factory(),
// ...
];

您可以在此处阅读有关工厂的更多信息:

如果要为每个创建的类别创建多个产品,可以执行以下操作:

//类别产品播种机
$categories=类别::工厂(50)->create();
$categories->each(功能$categories){
$categories->products()->saveMany(
产品::工厂(10)->make()
);
});

我得到未定义的$factory是否需要导入类?不知道是哪一个。与factory()函数相同,它表示未定义。我在使用laravel 8在laravel 8中,您可以使用Category::factory()而不是factory()辅助方法。并在类别模型中添加特征,使用HasFactory;是的,这就是我在文件中看到的。
Product::factory()
                ->has(Category::factory())->count(50)
                ->create();