Afshin Izadi
Afshin Izadi

Reputation: 526

laravel get all models with relations and the relations of these relations

block has two relations

1- one to many with region

2- one to many with seat

and the region has one to many relation with seat too so

3- region has one to many relation with seat too

this code

 $block=Block::with('regions','seats')->where('id',$blockId)->get();

will return this , it doesn't send regions relations

0 => Block {#457 ▼
  #relations: array:2 [▼
    "regions" => Collection {#460 ▼
      #items: array:1 [▼
        0 => Region {#463 ▼
          #relations: []
        }
      ]
    }
    "seats" => Collection {#471 ▶}

here the region has many seats and this code will nor return region seats. i can just get the block regions and seats while regions has many seats too.

should i get all regions id first and then try to get it all seats ? , is there any way to this ?

Upvotes: 6

Views: 12010

Answers (1)

Alexey Mezenin
Alexey Mezenin

Reputation: 163748

Use nested eager loading:

$block = Block::with('regions.seats', 'seats')->where('id', $blockId)->get();

Upvotes: 4

Related Questions