Many to Many vs Polymorphic relationships published 11/20/2019 | 4 min read

Hello everyone and welcome to a new story. Today we're discussing the differences between Many-to-Many and Polymorphic relationships as pros and cons.



Many to Many relationship (or belongs to many)

Many to many relationship comes up to mind immediately when you think of two entities that can relate to each other as of many records related to many records, something like the very common Tags example.

An article can have many tags, and a Tag can also have many many articles (or belongs to each others).

An Article with many Tags, and a Tag with many Articles, in this case, you can have a junction table like Articles_Tags with columns:

Now it's easy to link many Articles with many Tags using foreign keys. Now let's see pros and cons of this solution:

PROS:



CONS:

So in particular when having this scenario in 1st point in cons (more than 2 models), this is exactly where a polymorphic relationships kicks in, let's take a look into this.

Polymorphic relationship:

A polymorphic relationship is used when you want something like Many to Many relationship, but without having to create extra tables every time you want to add a new Model to the mix.

Polymorphic helps you combine all the junction tables into 1 very slim table, but at a cost.

So, let's take the same example of Articles and Tags above, but let's also add another Model called Songs.

With polymorphic we can have only 1 table to achieve that, the table should have these columns:

  1. ID (PK)
  2. TaggableID (INT)
  3. TaggableType (VARCHAR)

Now we can new records like:

  
{
  ID: 1,
  TaggableID: 7,
  TaggableType: "article"
}

A record for linking an article with a tag

and



  
{
  ID: 1,
  TaggableID: 8,
  TaggableType: "song"
}

A record for linking a song with a tag

Now let's explore pros and cons of this solution:

PROS:

CONS



Now, hope this story give you more insights on these 2 types of relationships, and help you decide which type to pick for your project.

Thanks for reading devspedia, I love you, and see you the next time :)



You may also like reading: