File tree Expand file tree Collapse file tree 3 files changed +35
-2
lines changed
src/Illuminate/Database/Eloquent/Factories Expand file tree Collapse file tree 3 files changed +35
-2
lines changed Original file line number Diff line number Diff line change @@ -69,7 +69,9 @@ protected function resolver($key)
69
69
{
70
70
return function () use ($ key ) {
71
71
if (! $ this ->resolved ) {
72
- $ instance = $ this ->factory instanceof Factory ? $ this ->factory ->create () : $ this ->factory ;
72
+ $ instance = $ this ->factory instanceof Factory
73
+ ? ($ this ->factory ->recycle ->get ($ this ->factory ->modelName ()) ?? $ this ->factory ->create ())
74
+ : $ this ->factory ;
73
75
74
76
return $ this ->resolved = $ key ? $ instance ->{$ key } : $ instance ->getKey ();
75
77
}
Original file line number Diff line number Diff line change @@ -68,7 +68,7 @@ abstract class Factory
68
68
*
69
69
* @var \Illuminate\Support\Collection
70
70
*/
71
- protected $ recycle ;
71
+ public $ recycle ;
72
72
73
73
/**
74
74
* The "after making" callbacks that will be applied to the model.
Original file line number Diff line number Diff line change @@ -670,6 +670,37 @@ public function test_model_instances_can_be_used_in_place_of_nested_factories()
670
670
$ this ->assertEquals ($ user ->id , $ post ->comments [1 ]->user_id );
671
671
}
672
672
673
+ public function test_for_method_recycles_models ()
674
+ {
675
+ Factory::guessFactoryNamesUsing (function ($ model ) {
676
+ return $ model .'Factory ' ;
677
+ });
678
+
679
+ $ user = FactoryTestUserFactory::new ()->create ();
680
+ $ post = FactoryTestPostFactory::new ()
681
+ ->recycle ($ user )
682
+ ->for (FactoryTestUserFactory::new ())
683
+ ->create ();
684
+
685
+ $ this ->assertSame (1 , FactoryTestUser::count ());
686
+ }
687
+
688
+ public function test_has_method_does_not_reassign_the_parent ()
689
+ {
690
+ Factory::guessFactoryNamesUsing (function ($ model ) {
691
+ return $ model .'Factory ' ;
692
+ });
693
+
694
+ $ post = FactoryTestPostFactory::new ()->create ();
695
+ $ user = FactoryTestUserFactory::new ()
696
+ ->recycle ($ post )
697
+ // The recycled post already belongs to a user, so it shouldn't be recycled here.
698
+ ->has (FactoryTestPostFactory::new (), 'posts ' )
699
+ ->create ();
700
+
701
+ $ this ->assertSame (2 , FactoryTestPost::count ());
702
+ }
703
+
673
704
/**
674
705
* Get a database connection instance.
675
706
*
You can’t perform that action at this time.
0 commit comments