首页 > 解决方案 > Laravel 8 数据库工厂

问题描述

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

例如,在 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 时,是否有办法在定义方法中获取这些属性?

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

标签: laravel-seedinglaravel-8factories

解决方案


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,
        ];
    }
}

推荐阅读