1. Home
  2. Many to Many vs Polymorphic relationships

Many to Many vs Polymorphic relationships

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:

  • ID (PK)
  • ArticleID (FK)
  • TagID (FK)

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:

  • Allows us to use foreign keys effectively.
  • Efficient data querying.
  • Maintains data consistency.

CONS:

  • More tables as each type requires a separate table – imagine adding Song to the mix, so you'll also need Songs_Tags in case you want to tag Songs too –.
  • Results in multiple classes, each representing the separate Type_Tags table.

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:

  • Easy to scale, more models can be easily associated with the polymorphic class.
  • No need for extra table when you add an extra Model to the mix.
  • Results in one class that can be used by many other classes (DRY).

CONS

  • More types can make querying more difficult and expensive as the data grows.
  • Cannot have a foreign key constrains (you can virtually insert any TaggableID and any TaggableType.
  • Lack of data consistency.
  • Weak ORM support.

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 :)