从3个表中获取数据(laravel Elount)
我有三张桌子,分别是:从3个表中获取数据(laravel Elount),laravel,eloquent,laravel-5.4,Laravel,Eloquent,Laravel 5.4,我有三张桌子,分别是: 酒店,酒店客房和酒店客房图片 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 |
酒店
,酒店客房
和酒店客房图片
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
Model
public function room()
{
return $this->hasMany('App\Models\HotelRoom', 'hotel_id');
}
public function images() {
return $this->hasMany('App\Models\HotelRoomImage', 'room_id');
}
HotelRoom.php
Model
public function room()
{
return $this->hasMany('App\Models\HotelRoom', 'hotel_id');
}
public function images() {
return $this->hasMany('App\Models\HotelRoomImage', 'room_id');
}
我可以通过Hotel.php
Model中的这个雄辩的查询获得所有有房间的酒店:
public function getHotelByToken($token)
{
return $this->with('room')
->where('token', $token)
->first();
}
我的问题:我想获得每个房间的详细信息及其各自的房间图像。我怎样才能做到这一点?任何帮助都将不胜感激。谢谢您可以通过以下方式获得所有带有图像的房间:
return $this->with('room.images')
->where('token', $token)
->first();
要加载嵌套关系,可以使用“点”语法
试试看
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
如果您正确定义了关系,那么您可以轻松获得所需的详细信息。我无法从链接到
hotelRoomImage.php
model的hotel.php
model中定义任何关系。在文档中查看一下,您会知道我可以获得房间图像,但我必须作为$hotel->roomImages
和$hotel->room
不同的是,我想在room属性中获取room images,这样我就可以通过$hotel->room->roomImages
访问它,因为对room
使用了一个多个,所以它总是返回一个集合,而不是一个实例。我猜那家酒店有不止一个房间?太好了!工作完美。这比我想象的更容易解决:)很高兴它有帮助。)