Laravel 工厂创建而不调用 afterCreating 回调

Laravel factory create without calling afterCreating callback

在编写测试时,我正在使用工厂 $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);
});

你可以在工厂中定义一个新的状态

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

然后你可以在state上定义after hook

$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();