首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Laravel Faker工厂关系

Laravel Faker工厂关系
EN

Stack Overflow用户
提问于 2021-04-03 12:24:57
回答 5查看 863关注 0票数 2

我有两家工厂,一家生产类别,另一家生产产品。当我运行工厂时,我想为生成的每个类别创建x个产品。我该如何编写代码来生产它呢?

类别的定义如下所示:

代码语言:javascript
复制
return [
            'name' => $this->faker->word,
            'slug' => Str::slug($this->faker->unique()->word, '-'),
        ];

产品的定义是这样写的:

代码语言:javascript
复制
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个项目

代码语言:javascript
复制
Category::factory()
                ->count(10)
                ->create();

我试了试,认为它可以工作,但我得到了一个错误,category_id cannot be null

代码语言:javascript
复制
Product::factory()
                ->has(Category::factory()->count(2))
                ->count(20)
                ->create();
EN

回答 5

Stack Overflow用户

发布于 2021-04-03 12:40:15

代码语言:javascript
复制
    $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也会懒洋洋地创建该模型,并自动关联它

票数 2
EN

Stack Overflow用户

发布于 2021-04-03 12:43:48

我正在使用一种不同的语法,但我认为它会起作用/你可以改变它

Category.php模型中

代码语言:javascript
复制
public function products() {
    return $this->hasMany(Product::class);
}

seeder

代码语言:javascript
复制
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

票数 2
EN

Stack Overflow用户

发布于 2021-04-03 13:22:06

您只需要向category_id传递一个CategoryFactory

代码语言:javascript
复制
return [
    'category_id' => Category::factory(),
    // ...
];

您可以在此处阅读有关工厂的更多信息:https://laravel.com/docs/8.x/database-testing#defining-relationships-within-factories

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66927714

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档