我本以为工厂创建是孤立的,所以我可以这样做:
factory(Ctow\User::class, 5)->each(function($user) {
// Add relations to 5 users created
});
factory(Ctow\User::class, 5)->each(function() {
// Add different relations to 5 different users created
// and not include the previously created users
// in the iteration
});
但是在种子中执行此操作:
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]);
});
从播种中得到的输出结果如下所示,但我以为它将仅包含一个记录final@example.com
,而不包含先前创建的用户:
// 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"]
如果在不同的种子文件中执行此操作,则结果将相同,因此根据使用的工厂和本地文件在文件中发生此错误。同样,使用关联的工厂状态创建时也会发生。
是否有一种方法可以隔离同一工厂调用之间的添加关系而不会发生这种情况?因此,我可以创建没有相关模型的用户,然后仅将关系添加到一些特定的模型中?