Seeding Polymorphic Pivot Tables

Posted 4 years ago by Ruffles

Hello there!

My team and I are working on a project and we have a few many to many polymorphic relationships.

So in order for me to put some dummy data into the database so we can show stuff on the screen, I have to seed all tables. I did seed all of them except for some bugs with the polymorphic pivot tables (aka many to many).

How would you go about writing the run() method?

Currently I wrote this:


use App\Models\Table1;
use App\Models\Table2;
use App\Models\Table3;
use Illuminate\Support\Facades\DB;


class TableableTableSeeder extends DatabaseSeeder
{
    protected $faker;
    protected $table1Ids;
    protected $table2Ids;
    protected $table3Ids;


    public function __construct()
    {

        $this->faker = Faker\Factory::create();
        $this->table1Ids = Table1::lists('id');
        $this->table2Ids = Table2::lists('id');
        $this->table3Ids = Table3::lists('id');

    }


    public function run()
    {

        for($i = 0; $i < 200; $i++)
        {

            DB::table('tableable')->insert([
                'table1_id' => $this->faker->randomElement($this->table1Ids),
                'tableable_id' => $this->faker->randomElement($this->randomModelId()),
                'tableable_type' => $this->randomModelName()
            ]);
        }
    }

    private function randomModelName()
    {
        $randomNumber = rand(0, 1);

        if ($randomNumber == 0)
        {
            return Table3::class;
        }

        elseif ($randomNumber == 1)
        {
            return Table2::class;
        }

    }


    private function randomModelId()
    {
        $randomNumber = rand(0, 2);

        if ($randomNumber == 0)
        {
            return $this->table3Ids;
        }

        elseif ($randomNumber == 1)
        {
            return $this->table2Ids;
        }

    }
}

Currently this works but the ids and the model names are not synced (which is obvious). I want to sync them so I don't get any nulls back when I populate the table. I am looking for some ideas here. Also, how would you do it with more than 2 models?

We are using version 5.0! (might update it to 5.1 later!)

Thanks!

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