Choosing the Right Database for Your Web Application
Learn how to choose the right database for your web application based on your project's requirements and constraints.
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 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:
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.
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:
Now we can new records like:
and
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 :)