因此,我真的很难为模型与用户和公司之间存在一对多关系的问题提出解决方案。这似乎有效,但是我敢肯定这不是最好的方法。这位于run()
的{{1}}方法中。
UsersTableSeeder
在上述情况下,作业具有public function run()
{
factory(App\User::class, 10)
->create()
->each(function ($user) {
$user->companies()->saveMany(
factory(App\Company::class, 10)->create(['user_id' => $user->id])->each(function($company) use ($user) {
$company->jobs()->save(factory(App\Job::class)->make([
'user_id' => $user->id,
'company_id' => $company->id,
]));
})
);
});
}
和user_id
。什么是更好(更简单)的方法?
答案 0 :(得分:0)
您可以从公司和用户模型中随机获得id
。像这样:
public function run()
{
factory(App\User::class, 10)
->create()
->each(function ($user) {
$user->companies()->saveMany(
factory(App\Company::class, 10)->create(['user_id' => $user->id])->each(function($company) use ($user) {
$company->jobs()->save(factory(App\Job::class)->make([
'user_id' => App\User::all()->random()->id,
'company_id' => App\Company::all()->random()->id,
]));
})
);
});
}