我本以为工厂创造是孤立的,所以我可以这样做:
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' => '[email protected]']);
factory(Ctow\User::class)->create(['username' => '[email protected]']);
factory(Ctow\User::class)->create(['username' => '[email protected]']);
factory(Ctow\User::class)
->create(['username' => '[email protected]'])
->each(function ($user) {
\Illuminate\Support\Facades\Log::info('USER', [$user->username]);
});
从下面看到的播种输出结果,但我认为它只包括单个记录[email protected]
,而不是之前创建的用户:
// Actual Result
[2019-02-17 22:52:05] local.INFO: USER ["[email protected]"]
[2019-02-17 22:52:05] local.INFO: USER ["[email protected]"]
[2019-02-17 22:52:06] local.INFO: USER ["[email protected]"]
[2019-02-17 22:52:06] local.INFO: USER ["[email protected]"]
// Expected Result
[2019-02-17 22:52:06] local.INFO: USER ["[email protected]"]
如果在不同的种子文件中执行此操作,则它具有相同的结果,因此它基于所使用的工厂以及本地在文件中发生。此外,使用关联的工厂状态创建时也会发生。
有没有办法隔离相同的工厂调用之间的添加关系而不发生这种情况?所以我可以创建没有相关模型的用户,然后只为几个特定的模型添加关系?
answer不会在单个模型创建中使用each
,因为它委托给构建器,因为模型没有each
方法。