0

在编写测试时,我正在使用工厂创建模型,$recipe = factory(Recipe::class)->create()但是每次创建配方时都会运行并添加关系的回调RecipeFactoryafterCreating

有没有办法跳过这个回调?我不希望创建任何关系。

RecipeFactory.phpafterCreating回调

$factory->afterCreating(Recipe::class, function ($recipe, Faker $faker) {
    $ingredients = factory(Ingredient::class, 3)->create();
    $recipe->ingredients()->saveMany($ingredients);
});
4

1 回答 1

1

您可以在工厂中定义新状态

$factory->state(Recipe::class, 'withRelations', [
    //Attributes
]);

然后你可以在状态上定义 after 钩子

$factory->afterCreating(Recipe::class, 'withRelations', function ($recipe, $faker) {
    $ingredients = factory(Ingredient::class, 3)->create();
    $recipe->ingredients()->saveMany($ingredients);
});

并删除现有的创建后挂钩。

现在,当您使用默认工厂时 - 不会创建任何关系。

$recipies = factory(Recipe::class, 5)->create();

但是,如果您还想创建相关记录 - 您可以使用withRelations状态

$recipiesWithRelations = factory(Recipe::class, 5)->state('withRelations')->create();
于 2020-12-08T07:41:17.533 回答