Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Laravel工厂创建而不调用创建后回调_Laravel_Laravel 5_Laravel Testing - Fatal编程技术网

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

Laravel工厂创建而不调用创建后回调,laravel,laravel-5,laravel-testing,Laravel,Laravel 5,Laravel Testing,在编写测试时,我使用工厂$recipe=factory(recipe::class)->create()创建一个模型,但是RecipeFactory具有afterCreating回调,该回调在每次创建配方时运行并添加关系 有没有办法跳过此回调?我不想建立任何关系 $recipies = factory(Recipe::class, 5)->create(); RecipeFactory.php创建回调后 $factory->afterCreating(配方::类,函数($Recipe,F

在编写测试时,我使用工厂
$recipe=factory(recipe::class)->create()
创建一个模型,但是
RecipeFactory
具有
afterCreating
回调,该回调在每次创建配方时运行并添加关系

有没有办法跳过此回调?我不想建立任何关系

$recipies = factory(Recipe::class, 5)->create();
RecipeFactory.php
创建回调后

$factory->afterCreating(配方::类,函数($Recipe,Faker$Faker){
$components=factory(component::class,3)->create();
$recipe->components()->saveMany($components);
});

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

$factory->state(配方::类,'withRelations'[
//属性
]);
然后可以在状态上定义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();
但是,如果您还想创建相关记录,则可以使用
with relations
状态

$recipiesWithRelations = factory(Recipe::class, 5)->state('withRelations')->create();

将测试代码包括在问题中,
factory->make()
可能会起作用