Laravel工厂和枢轴工作台播种

时间:2018-02-28 14:19:11

标签: database-design laravel-5.5 laravel-seeding

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

1 个答案:

答案 0 :(得分:1)

申请人_skill工厂没有必要 只需在创建申请人时获取技能的随机ID并附上

<强> ApplicantsTableSeeder.php

WITH data AS (SELECT DISTINCT name, Physics, Chemistry, Maths, Biology
  FROM `[Your_Project].[Your_dataset].[Your_table]`)
SELECT
  name,
  (CASE
  WHEN Physics >= Chemistry AND Physics >= Maths AND Physics >= Biology THEN Physics
  WHEN Chemistry >= Physics  AND Chemistry >= Maths AND Chemistry >= Biology THEN Chemistry
  WHEN Maths >= Physics AND Maths >= Chemistry AND Maths >= Biology THEN Maths
  WHEN Biology >= Physics AND Biology >= Chemistry AND Biology >= Maths THEN Biology
  ELSE Physics
  END) AS maxmark, 
  (CASE
   WHEN Physics >= Chemistry AND Physics >= Maths AND Physics >= Biology THEN 'Physics'
   WHEN Chemistry >= Physics  AND Chemistry >= Maths AND Chemistry >= Biology THEN 'Chemistry'
   WHEN Maths >= Physics AND Maths >= Chemistry AND Maths >= Biology THEN 'Maths'
   WHEN Biology >= Physics AND Biology >= Chemistry AND Biology >= Maths THEN 'Biology'
   ELSE 'Physics'
   END) as field
FROM
  data