Reputation: 1079
I have 3 tables namely:
hotels
, hotel_rooms
and hotel_room_images
hotels:
id | name | desc
1 | my hotel name | sth
hotel_rooms:
id | hotel_id | room_name
1 | 1 | my 1st room
2 | 1 | my 2nd room
hotel_room_images:
id | hotel_id | room_id | image
1 | 1 | 1 | my image
2 | 1 | 1 | my next image
1 | 1 | 2 | my image
2 | 1 | 2 | my next image
I have defined my relationships as below:
Hotel.php
Model
public function room()
{
return $this->hasMany('App\Models\HotelRoom', 'hotel_id');
}
HotelRoom.php
Model
public function images() {
return $this->hasMany('App\Models\HotelRoomImage', 'room_id');
}
I am able to get all hotels with rooms from this eloquent query in Hotel.php
Model:
public function getHotelByToken($token)
{
return $this->with('room')
->where('token', $token)
->first();
}
My Question: I want to get every room details and their respective room images. How can I achieve this? Any help would be greatly appreciated. Thank You
Upvotes: 1
Views: 2220
Reputation: 7489
Try it
public function rooms()
{
return $this->hasMany('App\Models\HotelRoom', 'hotel_id');
}
$hotel = Hotel::with('rooms.images')->find(1);
foreach($hotel->rooms as $room)
foreach($room->images as $image)
// you have single image here
endforeach
endforeach
Upvotes: 0
Reputation: 163748
You can get all rooms with images with:
return $this->with('room.images')
->where('token', $token)
->first();
To eager load nested relationships, you may use "dot" syntax.
https://laravel.com/docs/5.5/eloquent-relationships#eager-loading
Upvotes: 3