Concept of polymorphic model. For example we have this table comment:
+----+---------------+-------------------+------------------------------------+
| id | commentable_id| commentable_type | comments_text |
+----+---------------+-------------------+------------------------------------+
| 1 | 2 | youtube | youtube rocks, buddy! |
| 2 | 6 | vimeo | hey, vimeo is better! |
+--------------------+-------------------+------------------------------------+
- Where youtube and vimeo refer to the model
class Youtube(){…}andclass Vimeo(){…}youtube can has many comments, and vimeo can has many comments, and comment belong to youtube and vimeo. - If we want to add another model that has many comments in the future we just need to add that in
commentable_typewithout adding more field likesomething_idinto comment table. - If we want to add dailymotion, we just need to add dailymotion in
commentable_typewithout adding fielddailymotion_idinto comment table commentable_id = 2refer toyoutube_id = 2in youtube table, andcommentable_id= 6 refer tovimeo_id= 6 in vimeo table.
In Laravel (PHP) we can simply do like this:
class Youtube extends Eloquent{
public function comments()
{
return $this->morphMany('Comment', 'commentable');
}
}
class Vimeo extends Eloquent{
public function comments()
{
return $this->morphMany('Comment', 'commentable');
}
}
class Comment extends Eloquent{
public function commentable()
{
return $this->morphTo();
}
}
and we can simply access them like this:
$youtube = Youtube::find(1);
$youtube->comments;
$vimeo = Vimeo::find(1);
$vimo->comments;
My Questions are, how to derive the relationship of this ORM in ASP MVC? And how we can easily access them to do CRUD operation?
