H
H
hbuser2014-08-27 17:50:44
MySQL
hbuser, 2014-08-27 17:50:44

What are polymorphic relationships?

There is some information on the Internet, but all in the context of Ruby.
There is one-to-one, one-to-many, many-to-many. What are polymorphic relationships?
PS I am using Laravel. You can use her example.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman Sokharev, 2014-08-27
@hbuser

Suppose you have a comment that may be related to a (user) post or maybe related to a blog article.
Then your table might look something like this:
where:
comment_id - identifier of the comment itself
parent_id - identifier of the entity to which it belongs
morph - type of entity to which this comment refers.
comment_content , author - here I think it's clear
then the entries might look like this:

comment_id | parent_id | morph   | comment_content | author
---------------------------------------------------------------
  1        |   1       | post    | бла бла бла     | vasya
---------------------------------------------------------------
  2        |   1       | article | бла бла бла     | vasya
---------------------------------------------------------------

Moreover, despite the fact that they have the same parent_id , in the first case it refers to id in the post table , and in the second to article
This is called a polymorphic relationship.
I will give an example on the laravel framework for php (but the ORM there is very similar to Rails, so there should not be any problems)
The comment model will look something like this:
class Comment extends Eloquent {

 public function morph()
  {
     return $this->morphTo();
  }

}

and post and article models:
class Post extends Eloquent {

  public function photos()
  {
    return $this->morphMany('post', 'morph');
  }

}

class Article extends Eloquent {

  public function photos()
  {
    return $this->morphMany('article', 'morph');
  }

}

didn't seem to mess anything up...

T
tsarevfs, 2014-08-27
@tsarevfs

One of the options for implementing polymorphism:

create table Computer(
    id int not null,
    type varchar(20) not null,
    departmentId int not null references Department(id)
)
create table PC(
    id int not null references Computer(id),
    personId int not null references Person(id)
)
create table Notebook(
    id int not null references PC(id),
    dockId references Dock(id)
)

Maintaining such a structure in pure SQL can be quite laborious. This is most likely why most of the examples are written using various ORMs, including Rubi.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question