我有一个Hotel模型有很多Rooms那可以是occupied。我应该如何查询这个:
酒店列表
查询:
$hotels = Hotel::where('foo',$bar)
->withCount('rooms')
->withCount(['rooms' => function ($query) {
$query->where('status', 'Occupied');
}])
->get();
结果 :
$hotel->rooms_count
给出已占用房间的数量,这是最后一个withCount
表达。
我想要得到什么
作为第二个的别名withcount
:
Question
有没有办法alias第二withCount
在房间?
Although @jaysingkar's answer is a good way to go and answers the question pretty well, yes, it's possible to alias a withCount()
call although this hasn't been documented yet:
$hotels = Hotel::where('foo', $bar)
->withCount([
'rooms',
'rooms AS occupied_rooms' => function ($query) {
$query->where('status', 'Occupied');
}
])
->get();
这将为您提供$hotel->occupied_rooms_count
每家酒店的入住房间数。 :)
这个魔法发生的代码可以在这里看到 https://github.com/laravel/framework/blob/5.4/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php#L165。它是通过 Laravel 5.3.7 添加的公关#15279 https://github.com/laravel/framework/pull/15279.
Updated:我已经提交了 PR,现在正确记录 https://laravel.com/docs/5.4/eloquent-relationships#counting-related-models. :)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)