【问题标题】:Laravel 8 factory class is not overriding the parameters while creating the factoriesLaravel 8 工厂类在创建工厂时不会覆盖参数
【发布时间】:2021-01-26 03:40:08
【问题描述】:

我正在使用 Laravel 8 开发一个 Web 应用程序。我注意到 Laravel 8 中发生了很多变化,包括工厂。

我的 MenuCategory 模型类有一个工厂类 MenuCategoryFactory,其定义如下。

<?php

namespace Database\Factories;

use App\Models\Menu;
use App\Models\MenuCategory;
use Illuminate\Database\Eloquent\Factories\Factory;

class MenuCategoryFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = MenuCategory::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'name' => $this->faker->name,
            'menu_id' => Menu::factory()->create(),
        ];
    }
}

在我的代码(数据库播种器类)中,我试图在创建工厂时覆盖 menu_id,如下所示。

$restaurant = Restaurant::first();
        MenuCategory::factory()->create([
            'menu_id' => $restaurant->menu->id
        ]);

但它没有使用我传递的值,$restaurant->menu->id。相反,它正在创建一个新菜单。我的代码中缺少什么错误,我该如何解决?

【问题讨论】:

  • 我遇到了同样的问题。我发现你使用make 然后它会覆盖这些值......
  • make 方法不会持久化到数据库,而只是简单地创建对象/模型。这将用于测试。您必须自己持久化对象。
  • 遇到同样的问题,你解决了吗?

标签: laravel-8 laravel-factory


【解决方案1】:

在你的工厂定义中,不要调用-&gt;create(),而是这样设置:

public function definition()
    {
        return [
            'name' => $this->faker->name,
            'menu_id' => Menu::factory(),
        ];
    }

那么您应该能够像这样设置相关模型(假设您在模型中设置了关系):

$restaurant = Restaurant::first();
MenuCategory::factory()->for($restaurant)->create();

【讨论】:

    【解决方案2】:

    将定义改为

    public function definition()
        {
            return [
                'name' => $this->faker->name,
                'menu_id' => function() {
                     Menu::factory()->create()->id,
                }
            ];
        }
    

    然后你可以替换值

    【讨论】:

      猜你喜欢
      • 2020-05-30
      • 2021-02-02
      • 1970-01-01
      • 1970-01-01
      • 2021-01-14
      • 2021-01-04
      • 1970-01-01
      • 2023-03-03
      • 2021-04-25
      相关资源
      最近更新 更多