dimanche 17 février 2019

Laravel Factory

I would have thought that factory creation was isolated so I could do:

factory(Ctow\User::class, 5)->each(function($user) { 
  // Add relations to each $user created
});
factory(Ctow\User::class, 5)->each(function() { 
  // Add different relations to each $user created
  // and not include the previously include users
  // in the iteration
});

But performing this in a seed:

factory(Ctow\User::class)->create(['username' => 'test1@example.com']);
factory(Ctow\User::class)->create(['username' => 'test2@example.com']);
factory(Ctow\User::class)->create(['username' => 'test3@example.com']);

factory(Ctow\User::class)
    ->create(['username' => 'final@example.com'])
    ->each(function ($user) {
        \Illuminate\Support\Facades\Log::info('USER', [$user->username]);
    });

Results in the output below, but I would have thought the output would only be final@example.com, and not include the previous created users:

// Actual Result
[2019-02-17 22:52:05] local.INFO: USER ["test1@example.com"] 
[2019-02-17 22:52:05] local.INFO: USER ["test2@example.com"] 
[2019-02-17 22:52:06] local.INFO: USER ["test3@example.com"] 
[2019-02-17 22:52:06] local.INFO: USER ["final@example.com"] 

// Expected Result

[2019-02-17 22:52:06] local.INFO: USER ["final@example.com"] 

If you do this in different seed files it has the same result so it occurs across files based on the factory used, as well as, locally. Also, occurs when created using states.

Is there a way to isolate adding relationships between factories invocations without this occurring? So I can create users that have no related models, and then add relations to only a few specific ones?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire