如何更改使用工厂创建的嵌套实体的默认值?

问题描述 投票:0回答:1

我的数据模型如下所示:

一个订单包含 1 到 N 个

Products
,一个
Product
有一个
Category

我有 3 个工厂,每个实体一个:

OrderFactory
ProductFactory
CategoryFactory
。在其中,我设置了默认数据:

namespace Database\Factories;

use App\Category;
use App\Product;
use Illuminate\Database\Eloquent\Factories\Factory;

class ProductFactory extends Factory
{
    protected $model = Product::class;

    public function definition()
    {
        $name = $this->faker->realText(20);
        return [
            'category_id' => Category::factory(),
            'reference' => str_replace(' ', '', $name),
            'name' => $name,
            'price' => $this->faker->randomFloat(2, 1.00, 200.00),
        ];
    }
}
namespace Database\Factories;

use App\Category;
use Illuminate\Database\Eloquent\Factories\Factory;

class CategoryFactory extends Factory
{
    protected $model = Category::class;

    public function definition()
    {
        return [
            'label' => $this->faker->realText(20),
            'description' => $this->faker->text,
        ];
    }
}

我想要一个特定的测试来创建一个订单,其中包含名为

Category
my specific category label
的 5 个产品。我尝试这样做:

$order = Order::factory()
    ->state([
        'number' => 014789012,
    ])
    ->has(
        Product::factory()
            ->count(3)
            ->has(
                Category::factory()->state([
                    'label' => 'my specific category label',
                ])
            )
    )
    ->create();

Category->label
未编辑,仍保留
CategoryFactory
中定义的默认值。为什么?

php laravel phpunit laravel-factory php-faker
1个回答
0
投票

我在

has()
 
for()
 关系上使用 
Product<=> 而不是
Category
犯了一个错误:因为它是 OneToMany 关系,所以我们需要使用
for()
,如下所示:

$order = Order::factory()
    ->state([
        'number' => 014789012,
    ])
    ->has(
        Product::factory()
            ->count(3)
            ->for(
                Category::factory()->state([
                    'label' => 'my specific category label',
                ])
            )
    )
    ->create();
© www.soinside.com 2019 - 2024. All rights reserved.