Laravel 5: Eloquent – relationship types: many models to many models example

Eloquent: relationship types: many models to many models example

I will explain here:

  • how parameters in polymorphic relations work
  • how to relate many models on many models
many-to-many: one model with many

Most basic use of polymorphic relation is when you have single model commanding data of many models.

We have main model Seller working with models Ebook and Reader.

For such relationship, we build piwot table looking like this:

‘seller_id’
We have out column ‘seller_id’ that is compared against column ‘id’ of table ‘sellers’ – one model Seller is working with.

‘flagable_id’
Name is unimportant, could be selable_id, or anything else.
This column works with ‘id’ column from table defined in ‘flagable_type’, e.g. table ‘ebooks’.

‘flagable_type’
This column describes which model we are comparing against.


many-to-many: many models with many

But sometimes, you may want to work many tables against many tables, e.g.:

In this case we build more than one column for main models:

  • seller_id (model Seller, table sellers)
  • distributor_id (model Distributor, table distributors)

The whole trick is how you define relationship methods in your related models.

Just see sample models below, read comments and see tables.

Pivot (with extra column for distributor):

Table sellers:

Model Seller:

Table distributors:

Model Distributor:

Table ebooks:

Model Ebook:

Table readers:

Model Reader:

Usage:

Getting pivot data: