我有一个Laravel ORM查询,我将2-3关系连接在一起,如下所示:
$data = AccommodationRoom::with('accommodation.city',
'accommodation.accommodationFacilities', 'accommodation.gallery')
->whereHas('roomCapacityHistory', function ($query) use ($from_date, $to_date) {
$query->whereDate('from_date', '<=', $from_date);
$query->whereDate('to_date', '>=', $to_date);
})
->whereHas('accommodation', function ($query) use ($searchCity) {
$query->where('city_id', $searchCity);
})
->limit(10)->get();
return response()->json($data, 200);
在房间模型上,我检查容量模型是否有日期,以及城市ID是用户提供给酒店(住宿)的位置。问题是,当我得到结果时,每个房间都会得到重复的酒店。对于一次搜索,我可能会得到十家相同的酒店,因此我想使住宿变得唯一,并为每个住宿显示一个结果(房间)。
答案 0 :(得分:1)
您可以使用groupBy而不是distinct;因为您要基于一个列对结果进行分组,例如,accommodation_id:
$data = AccommodationRoom::with('accommodation.city',
'accommodation.accommodationFacilities', 'accommodation.gallery')
->SELECT('accommodation_id')
->whereHas('roomCapacityHistory', function ($query) use ($from_date, $to_date) {
$query->whereDate('from_date', '<=', $from_date);
$query->whereDate('to_date', '>=', $to_date);
})
->whereHas('accommodation', function ($query) use ($searchCity) {
$query->where('city_id', $searchCity);
})
->groupBy('accommodation_id')->limit(10)->get();
return response()->json($data, 200);
答案 1 :(得分:0)
尝试链接distinct method。
即:
$data = AccommodationRoom::with('accommodation.city',
'accommodation.accommodationFacilities', 'accommodation.gallery')
->whereHas('roomCapacityHistory', function ($query) use ($from_date, $to_date) {
$query->whereDate('from_date', '<=', $from_date);
$query->whereDate('to_date', '>=', $to_date);
})
->whereHas('accommodation', function ($query) use ($searchCity) {
$query->where('city_id', $searchCity);
})
->distinct('VALUE_FOR_HOTEL_HERE')->limit(10)->get();
return response()->json($data, 200);