我想获取工厂中的覆盖属性,这些属性是在使用工厂时在seeder中定义的。
例如,在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时,有没有在定义方法中获取这些属性的方法?
任何想法都会很有帮助。谢谢!
发布于 2020-10-05 12:49:31
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,
];
}
}发布于 2021-06-05 22:34:26
这个特性在Laravel 8中已经消失了,但是你仍然可以用afterMaking()或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-02-13 03:18:39
事实上,它的工作方式与以前一样。
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,
}祝你有愉快的一天?
https://stackoverflow.com/questions/64114751
复制相似问题