Recently I have been trying to seed my database using Laravel seeding through Model Factories and Faker.
对于简单的模式,让它工作起来很容易:).然而,在使用复杂的数据库模式时,我遇到了几个问题,涉及foreign keys and table relationships个:
- 一对一
- 一对多
- Many to Many
...如链接中所述:
在本主题中,official documentation建议按如下方式运行数据库种子:
public function run()
{
factory(App\User::class, 50)->create()->each(function ($u) {
$u->posts()->save(factory(App\Post::class)->make());
});
}
... but there is one problem with this solution: when working with many DB tables and running many seeds (with many relations between them), it is common to create many unnecessary models using this methodology. For instance, if we had run the PostsTableSeeder.php before the one of the above example, all those posts would not have been linked to users, and would never be used in tests and development...
So searching for a way to handle this situation, I have come up to a functional solution that works for me and avoids the unnecessary creation of those 'orphan' models...
And I wanted to share it with everyone, so it is just explained in the answer :).