I have a table contents which has many types, for example posts , albums, videos.
the contents table migration is :
Schema::create('contents', function (Blueprint $table) {
$table->increments('id');
$table->integer('ref_id')->index();
$table->integer('type')->index();
$table->string('title', 255);
$table->text('description');
$table->boolean('published')->default(false);
$table->string('thumb', 255);
$table->timestamps();
});
and posts table migration is:
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->text('body');
});
the same idea goes for all other types like videos:
Schema::create('videos', function (Blueprint $table) {
$table->increments('id');
$table->string('youtube_id', 255);
});
To retrieve the full content now, I use hasMany relationship:
class Content extends Model
{
public function posts() {
return $this->hasMany('App\Post','id' ,'ref_id');
}
public function videos() {
return $this->hasMany('App\Video','id' ,'ref_id');
}
...
}
class Post extends Model
{
public function content() {
return $this->belongsTo('App\Content', 'id' , 'ref_id')->where('type','1');
}
}
class Video extends Model
{
public function content() {
return $this->belongsTo('App\Content', 'id' , 'ref_id')->where('type','3');
}
}
As you can see, I manually added types where each type has a number , for example, content with type 1 is for posts, content with type 3 is for videos, etc..
I feel like my structure isn't that good and can be improved. I came across Polymorphic Relations in the documentation and I don't know if it will be good for my case or not.
Any Advice?