Laravel 5: Eloquent – relationship types: has many through

Eloquent: relationship types – has many through

DB tables used in examples: here.

hasManyThrough

Has-many-through:
Resembles a bit pivot table relationship. Only difference is that some existing table is used as a logical connector between two tables that lack direct connection.
Sample table structure

Lets say we want to check how many votes comments for given post got.
There is no direct connection between ‘posts‘ and ‘votes‘, so we will have to use some intermediate table to connect these two.

Here are structures of tables with relevant columns.

Distant relation between models: hasManyThrough()

So, we will use ‘comments’ table as our intermediate (quasi-pivot) table, using its keys: id, post_id as hooks, to inter-relate models post and vote.

Our hasManyThrough() location and sample

This method goes into our main model: POST.

Lets explain hasmanyThrough() method arguments:

Legend:

  1. main model: Post
  2. intermediate model: Comment
  3. final model: Vote

Now, arguments from hasmanyThrough() relationship and how they relate to each other.

argument #1 (comments.post_id)
field from intermediate: intermediate model relationship to main model – should relate with arg. #3

argument #2  (votes.comment_id)
field from final: final model relationship to intermediate model – should relate with arg. #4

argument #3  (post.id)
field from main: main model relationship to intermediate model – should relate with arg. #1

argument #4  (comments.id) (available since L5.5 – before defaulted to primary)
field from intermediate: intermediate model relationship to final model – should relate with arg. #2

 

how to use it
Access data via Post object.
We can use Eloquent dynamic property.

Above example allows to get Vote object data for given instance of Post via intermediate Comment model.