我有3张桌子Applicant
,Skills
和Applicant_skill
。这里Applicant_skill
是数据透视表。一个申请人有很多技能。我想写下面的工厂。
**ApplicantSkillFactory.php**
<?php
use Faker\Generator as Faker;
$factory->define(App\Applicant_skill::class, function (Faker $faker) {
return [
'applicant_id' => \App\Applicant::all()->random()->id,
'skill_id' => \App\Skills::all()->random()->id,
];
});
ApplicantsTableSeeder.php
<?php
use Illuminate\Database\Seeder;
class ApplicantsTableSeeder extends Seeder
{
public function run()
{
factory(App\Applicant::class,20)->create()->each(function ($u) {
$u->Applicant_skill()->associate(factory(App\Applicant_skill::class)->make());
});
}
}
现在我该如何播种这3张桌子?
Applicant_skill工厂不需要 在创建申请人时,只需从技能中获取随机ID并附加
ApplicantsTableSeeder.php
<?php
use Illuminate\Database\Seeder;
class ApplicantsTableSeeder extends Seeder
{
public function run()
{
factory(App\Applicant::class,20)->create()->each(function ($a) {
$a->Applicant_skill()->attach(
\App\Skills::all()->random()->id
);
});
}
}