2

我想在使用工厂时在播种机中定义工厂中的覆盖属性。

例如,在 Laravel 7 中,可以将它们作为第三个参数

$factory->define(Menu::class, function (Faker $faker, $params) {
      /* here params have the override attributes, which can be used to specify other attributes based on it's value, for example menu_type */
}

现在升级到 laravel 8 时,是否有办法在定义方法中获取这些属性?

任何想法都会有所帮助。谢谢!

4

3 回答 3

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

    /**
     * Define the model's default state.
     *
     * @return array
     */
    //
    public function definition() {
        return [
            'user_id' => function(){
                return User::factory()->create()->id;
            },
            'title' => $this->faker->title,
            'body' => $this->faker->sentence,
        ];
    }
}
于 2020-10-05T04:49:30.823 回答
1

此功能在 Laravel 8 中已丢失,但您仍然可以使用afterMaking()or 或 a获得相同的结果custom state

class MenuFactory extends Factory {
  public function configure()
  {
    return $this->afterMaking(function (Menu $menu) {
      /* Here `$menu` has the override attributes, 
         which can be used to specify other attributes based on its value, 
         for example `menu_type` */
    });
  }
}
于 2021-06-05T14:34:26.327 回答
0

事实上,它的工作方式与以前相同。

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

    public function definition() {
        return [
            'name' => $attributes['name'] ?? $this->faker->name,
            'available' => $attributes['available'] ?? false,
        ];
    }
}

修补匠

App\Models\Menu::factory()->make(['name' => 'lorem'])
=> App\Models\Menu {#3346
     name: "lorem",
     available: true,
   }

App\Models\Menu::factory()->make()
=> App\Models\Menu {#3346
     name: "Prof. Theodora Kerluke",
     available: true,
   }

祝你今天过得愉快

于 2021-02-12T19:18:38.687 回答