Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

hondnl's avatar

Polymorphic Tables, but different.

Hi ,

Let's say we have 3 tables : titles,movies,tv_shows

  Schema::create('titles', function (Blueprint $table) {
            $table->increments('id'); // referenced as t_id
            $table->string('name');
            $table->tinyInteger('category');
            $table->unsignedSmallInteger('year')->index();
            $table->timestamps();
        });
   Schema::create('movies', function (Blueprint $table) {
            $table->increments('id');

            $table->unsignedInteger('t_id')->unique(); // titles id

           // extra columns
            $table->smallInteger('runtime')->nullable();
            $table->string('genres')->nullable();
            $table->tinyInteger('rating')->nullable();
            $table->timestamps();
        });
   Schema::create('tv_shows', function (Blueprint $table) {
            $table->increments('id');

            $table->unsignedInteger('t_id')->unique(); // titles id

        //  Extra columns
            $table->string('lang',50)->nullable()->index();
            $table->string('status',50)->nullable()->index();
            $table->smallInteger('runtime')->nullable();
            $table->date('first_aired')->nullable();
            $table->string('genres')->nullable();
            $table->string('url')->nullable();
            $table->unsignedTinyInteger('rating')->nullable();
            $table->unsignedInteger('network_id')->nullable()->index();
            $table->text('plot')->nullable();
            $table->smallInteger('season_type')->nullable();
            $table->timestamps();
        });

the titles category , is set as : 1=movie , 2=tv show We insert two titles into our db. One is a movie , the other is a tv show, so : category =1 && category= 2

Now ideally I would want something like this.

$titles = App\Title::with('info')->get();

foreach ($titles as $title) {

    // Where Title 1 ( movie) would give the row from table movies.
   // Where Title 2 ( tv show) would give the row from table tv_shows
    
     dump($title->info);
}

So that if you take a look at https://laravel.com/docs/5.6/eloquent-relationships#polymorphic-relations the type would be the titles.category ( movie or tv show) and the id would be the t_id ( titles.id).

Is this achievable with laravel ?

Thanks

0 likes
1 reply
staudenmeir's avatar

You can try it with a custom $morphMap, but I would recommend you to use the models' classes (or abbreviations) instead of integers.

The t_id column belongs into the titles table (like commentable_id in the documentation example).

Please or to participate in this conversation.