Mysql 拉雷维尔酒店预订量居前
有一个酒店预订申请,我需要得到4个最热门的预订酒店 我与Reservation.php中的酒店有关系Mysql 拉雷维尔酒店预订量居前,mysql,laravel,Mysql,Laravel,有一个酒店预订申请,我需要得到4个最热门的预订酒店 我与Reservation.php中的酒店有关系 public function hotel(){ return $this->belongsTo('App\Hotel'); } 我可以通过以下查询实现我想要的: Reservation::select(DB::raw('*, COUNT(hotel_id) as hotel_count'))->with('hotel')->groupby('hote
public function hotel(){
return $this->belongsTo('App\Hotel');
}
我可以通过以下查询实现我想要的:
Reservation::select(DB::raw('*, COUNT(hotel_id) as hotel_count'))->with('hotel')->groupby('hotel_id')->orderby('hotel_count', 'desc')->limit(4)->get();
是否有任何简化版本可用于上述查询
更新:数据库结构
在您的
Hotel.php
模型中查看
public function reservation()
{
return $this->hasMany('App\Reservation');
}
在控制器中,您可以通过
Hotel::withCount('reservation')->orderBy('reservation_count', 'desc')->limit(4)->get();
@GopiChand,很好用。但是我听说了withcount(),但我不能在这里使用它。在整数上调用成员函数getRelationExistenceCountQuery()时出现此错误更改了我的答案,请重新检查旅行版本顺便说一句?我已添加了预订表的db结构。是否错过了此错误<代码>groupby(“酒店id”)
Hotel::withCount('reservation')->orderBy('reservation_count', 'desc')->limit(4)->get();