我正在尝试使用 Factory 创建模型后对其进行修改。我已经定义了configure()方法,并在其中定义了我想要在模型中更改的内容。但是,Laravel 不会调用它,它会保存未修改的原始值。如何解决这个问题?
这是 MealFactory 中的配置函数:
public function configure()
{
return $this->afterCreating(function (Meal $meal) {
$meal->setTranslation('title', 'hr', 'Croatian translation' . $meal->getId())
->setTranslation('title', 'de', 'German translation' . $meal-getId());
});
}
在台式播种机中,我这样称呼它:
$meals = $mealFactory
->count(15)
->create();
根据https://github.com/Illuminate/database/blob/master/Eloquent/Factories/Factory.php
方法配置仅在调用方法 new 时调用,在当前版本中仅在调用 times 时调用,因此在您的情况下应该使用:
$mealFactory
->times(15)
->create();
正如 Влад Киевский 所提到的,
configure()
只能从 new()
调用,因此请确保您使用 new()
来实例化工厂类。
// Don't use
$mealFactory = new MealFactory();
// Use instead
$mealFactory = MealFactory::new();
在
$meal->save()
回调结束时调用 afterCreating
。
考虑以下代码;
return $this->afterCreating(function (Meal $meal) {
$meal->setTranslation('title', 'hr', 'Croatian translation' . $meal->getId())
->setTranslation('title', 'de', 'German translation' . $meal-getId());
// Save
$meal->save();
});
如果您在模型中定义了
newFactory
,请确保它使用 Factory::new()
而不是 new Factory
protected static function newFactory(): UserFactory
{
return UserFactory::new();
}