Laravel工厂和枢轴工作台播种

问题描述 投票:0回答:1

我有3张桌子ApplicantSkillsApplicant_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张桌子?

database-design laravel-5.5 laravel-seeding
1个回答
1
投票

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
            );
        });
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.