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

时间:2018-01-06 11:03:17

标签: laravel eloquent laravel-5.4

我有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');
 }

我可以通过Hotel.php模型中的这个雄辩查询获得所有带房间的酒店:

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

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

2 个答案:

答案 0 :(得分:3)

您可以使用以下图片获取所有客房:

return $this->with('room.images')
            ->where('token', $token)
            ->first();
  

要急切加载嵌套关系,您可以使用" dot"句法。

https://laravel.com/docs/5.5/eloquent-relationships#eager-loading

答案 1 :(得分:0)

试试吧

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