我有一个查询,我正在加载3个关系,如下所示:
$data = Hotel::with('rooms.discount')
->whereHas('rooms.discount')->paginate(10);
return DiscountResource::collection($data);关系如下:
public function Rooms()
{
return $this->Hasmany(Room::class);
}以及与房间的折扣关系
public function discount()
{
return $this->belongsTo(Discount::class, 'id', 'room_id');
}例如,现在每家酒店都有50家酒店,其中只有1个房间有我想要的折扣,这段代码现在显示了他们有折扣或没有折扣的所有房间,如果没有,则显示为null,但我不想在我的API中显示没有折扣的房间,因为这会使它变得很重。
发布于 2019-09-28 23:26:16
现在看起来tablea是这样实现的:
Hotelid,Roomid,hotel_id,Discountid,room_id
这意味着Rooms>Discount不是belongsTo() ->它是hasMany(),因此应该命名为: Room->Discounts() -所以一个房间有几个折扣:
public function discounts()
{
return $this->hasMany(Discount::class, 'id', 'room_id');
}基于此-可以在酒店中再放置一个关系:
public function roomDiscounts()
{
return $this->hasManyThrough(Discount::class, Room::class, 'hotel_id', 'room_id', 'id', 'id');
}因此,您想要查找所有房间有折扣的酒店:
$hotels = Hotel::whereHas('roomDiscounts')->get();希望这能有所帮助。
https://stackoverflow.com/questions/58146402
复制相似问题