我有一个酒店模型,有许多房间可以被占用。我该如何查询:
酒店列表
查询:
$hotels = Hotel::where('foo',$bar)
->withCount('rooms')
->withCount(['rooms' => function ($query) {
$query->where('status', 'Occupied');
}])
->get();
结果:
$hotel->rooms_count
给出占用房间的数量,这是最后一个 withCount
表达式。
我想要得到什么
$hotel->rooms_count
作为每家酒店的房间数
$hotel->occupied_rooms_count
为各酒店入住房间数
作为第二个
withcount
的别名:
有没有办法在房间上设置alias第二个
withCount
?
虽然@jaysingkar的答案是一个很好的方法并且很好地回答了问题,但是,是的,可以为
withCount()
调用别名:
$hotels = Hotel::where('foo', $bar)
->withCount([
'rooms',
'rooms AS occupied_rooms' => function ($query) {
$query->where('status', 'Occupied');
}
])
->get();
这将为您提供
$hotel->occupied_rooms_count
以及每家酒店的入住房间数。 :)
发生这种魔法的代码可以在这里看到。它是通过 PR #15279 添加到 Laravel 5.3.7 中的。
我已经提交了 PR,现在已正确记录了。
不要在
where
中指定 withCount
子句,而是在 Hotel
模型中定义占用房间的关系。
public function occupied_rooms(){
return $this->hasMany(Room::class)
->where('status', 'Occupied');
}
现在,在您的控制器中使用,
withCount('occupied_rooms')
。
$hotels = Hotel::where('foo',$bar)
->withCount(['rooms','occupied_rooms'])
->get();
$hotels = Hotel::where('foo',$bar)
->withCount('rooms AS rooms_count')
->withCount(['rooms AS occupied_rooms_count' => function ($query) {
$query->where('status', 'Occupied');
}])
->get();