从 3 个表中获取数据 (laravel eloquent)

Get data from 3 tables (laravel eloquent)

我有 3 个表: hotelshotel_roomshotel_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

我将我的关系定义如下:

Hotel.php 型号

public function room()
{
    return $this->hasMany('App\Models\HotelRoom', 'hotel_id');
}

HotelRoom.php 型号

public function images() {
    return $this->hasMany('App\Models\HotelRoomImage', 'room_id');
 }

我可以从这个 eloquent 查询中获得所有有房间的酒店 Hotel.php 型号:

public function getHotelByToken($token)
{
   return $this->with('room')
                ->where('token', $token)
                ->first();
    }

我的问题:我想获取每个房间的详细信息及其各自的房间图片。我怎样才能做到这一点?任何帮助将不胜感激。谢谢

您可以获得所有带有图像的房间:

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

试一试

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