[英]Laravel get top booked hotel count
Having a hotel booking application and i need to get the 4 top booked hotels. 有酒店预订应用程序,我需要获取4家顶级预订酒店。
i have a relationship, to hotel in the Reservation.php 我有一个关系,酒店在Reservation.php
public function hotel(){
return $this->belongsTo('App\Hotel');
}
I can achieve what i wanted with the following query: 我可以通过以下查询实现我想要的:
Reservation::select(DB::raw('*, COUNT(hotel_id) as hotel_count'))->with('hotel')->groupby('hotel_id')->orderby('hotel_count', 'desc')->limit(4)->get();
Is there any simplified version is available to the above query? 以上查询是否有任何简化版本?
Update: Db structure 更新:Db结构
Reservation::withCount('hotel')->orderBy('hotel_count', 'desc')->take(4)->get();
看看https://laravel.com/docs/5.6/eloquent-relationships#counting-related-models
In your Hotel.php
model 在您的
Hotel.php
模型中
public function reservation()
{
return $this->hasMany('App\Reservation');
}
In your controller you can access by 在您的控制器中,您可以通过
Hotel::withCount('reservation')->orderBy('reservation_count', 'desc')->limit(4)->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.