Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

protarr's avatar

Traverse models in multiple levels using Laravel's eloquent

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.

0 likes
3 replies
andiliang's avatar
Level 39

hi yes you do it

look like you are looking for hasmany through relashiption

official doc https://laravel.com/docs/8.x/eloquent-relationships#has-many-through

let sy table a is contry , table b is use , table C is post ,

a contry has many user , a user belongs a contry a user has many post , a post belong to a user

in contry model you can do this :

class Country extends Model { /** * Get all of the posts for the country. */ public function posts() { return $this->hasManyThrough('App\Models\Post', 'App\Models\User'); } }

example above from laravel thanks

1 like

Please or to participate in this conversation.