Laravel 5: Eloquent – difference between polymorphic relations

Eloquent: difference between polymorphic relations

Difference between simple polymorphic relations and many to many polymorphic relations comes down to pivot table.
simple polymorphic relations
This polymorphic relation can work only on one-to-one basis.

You have one table (model) handling data for two, or more models.
Data is assigned to to data from another table (model), but it cannot serve multiple models.

Lets see these 3 tables to demonstrate example.

ebooks table:

readers table:

comments table:

Comments table, is a quasi-pivot table.
Quasi, because besides pivot columns: commentable_id and commentable_type it has also data table: body.

Since data is firmly attached to pivot values, it can serve only single dataset (model instance).

Example:
Dataset 2:
Reader (row #2 from comments table) can only hold comment for item with id 2 from readers table – which is Kindle.
Dataset 3:
Ebook (row #3 from comments table) can only hold comment for item with id 2 from ebooks table – which is 2001: A Space Odyssey by Arthur C. Clarke.

So, this polymorphic relation can work only on one-to-one basis and quasi-pivot table with data-load is just a convenient data holder for multiple models.

See here how to use it.

many to many polymorphic relations
This polymorphic relation can work only on many-to-many basis.

You have one table (model) handling data for multiple models via pivot table, which allows data to serve multiple models.

Lets say we have some multiple tables:

  • ebooks and
  • readers

Data from our multiple tables can be tagged by data from single table.
Ebooks and readers can be sold by many sellers, like:

  • ebay
  • amazon
  • allegro

Ebooks are held by table like an example one a bit above on this page.
Readers are held by table like like an example the one just above.

Sellers are held by separate table, that look like this:

Now, each ebook / reader can be sold by multiple retailers.
So, to connect them together, we need some sort of pivot table.
Here is our sample pivot table:

Lets explain table above:

  • seller_id
    holds foreign key from sellers table
    its name consists of:

    • lowercase name of model working with sellers table, in this case ‘seller’
    • suffix ‘_id’
  • saleable_id
    this is a foreign key from table described by model in next column
  • saleable_type
    name of table joined described by model name

See here how to use it.