protarr
1 month ago

Traverse models in multiple levels using Laravel's eloquent

Posted 1 month ago by protarr

I am using Laravel 8.

Suppose we have 3 tables. table_a, table_b and table_c.

A simple 3 levels of tables. Table A has many B and table B has many C.

table_a
  id
  name
  
table_b
  id
  table_a_id
  name
  
table_c
  id
  table_b_id
  name

I configured in TableA model a method tableB pointing to TableB model using hasMany. It works. I can retrieve the table_b records just using TableA::find(1)->tableB .

I configured in TableB model a method tableC pointing to TableC model using hasMany. It works. I can retrieve the table_c records just using TableB::find(1)->tableC .

Can I retrieve in one step all table_c records related to a table_a record ?

e.g.

Something like TableA::find(1)->... (i need the related records in table_c)

Thank you.

Please sign in or create an account to participate in this conversation.