Solution 1: Simplify the Relationship

Let's learn how we can simplify the DB relationships to avoid Polymorphic Association antipattern.

It’s better to redesign our database to avoid the weaknesses of Polymorphic Associations but still be able to support the data modeling we need. We will be seeing a few solutions that accommodate the data relationship but make better use of metadata to enforce integrity. These are:

Reverse the reference

One solution to this antipattern is simple once the nature of the problem becomes evident: Polymorphic Associations are backward.

Creating intersection tables

A foreign key in the child table Comments can’t reference multiple parent tables, so, instead, we use multiple foreign keys to reference the Comments table. To do this, we create a separate intersection table for each parent table. In each intersection table, we include a foreign key to Comments and a foreign key to the respective parent table.

Get hands-on with 1200+ tech skills courses.