Factory for Pivot Table

Published 6 months ago by afoysal

I have 3 tables Applicant,Skills and Applicant_skill. Here Applicant_skill is the pivot table. One Applicant has many Skills. I am trying to write factory like below.

https://gist.github.com/afoysal/80428e36c87a1c4f3fceb8a1ce19658e

Is there any mistake in the Factory code ?

Snapey
Snapey
6 months ago (998,255 XP)

Better here... you are more likely to get a reply

ApplicantSkillFactory

<?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,
    ];
});

This will not give you what you want since each time you run it you have just as much chance to pick an applicant and skill as the last time you ran it. You will end up with some applicants with no skills at all, and some with the same skills repeated over and over.

Can you tell me when you want to use this?

afoysal

Thanks @Snapey for your reply. I am new in factory and seeding. I am fighting with these factory and seeding for last few days. I have to learn more about factory and seeding. I have 3 tables Applicant,Skills and Applicant_skill. Here Applicant_skill is the pivot table. One Applicant has many Skills.

I have 3 seeder like below

<?php

use Illuminate\Database\Seeder;

class ApplicantSkillTableSeeder extends Seeder
{

    public function run()
    {
        factory(App\Applicant_skill::class,10)->create();
    }
}
<?php

use Illuminate\Database\Seeder;

class SkillsTableSeeder extends Seeder
{
    public function run()
    {
        factory(App\Skills::class,10)->create();
    }
}
<?php

use Illuminate\Database\Seeder;

class ApplicantsTableSeeder extends Seeder {
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run() {

        factory(App\Applicant::class, 20)->create()->each(function ($u) {
            $u->Applicant_skill()->sync(\App\Skills::all()->random()->id);
    }
}

I don't know whether my seeders are correct or not. Thanks.

Please sign in or create an account to participate in this conversation.