Laravel OrderBy relationship count

后端 未结 5 941
Happy的楠姐
Happy的楠姐 2020-11-28 06:24

I\'m trying to get the most popular hackathons which requires ordering by the respective hackathon\'s partipants->count(). Sorry if that\'s a little difficul

5条回答
  •  爱一瞬间的悲伤
    2020-11-28 07:05

    You can also use join operator. As Sabrina said, you can not use sortby at the db level.

    $hackathons = Hackathon::leftJoin('hackathon_user','hackathon.id','=','hackathon_user.hackathon_id')
               ->selectRaw('hackathon.*, count(hackathon_user.hackathon_id) AS `count`')
               ->groupBy('hackathon.id')
               ->orderBy('count','DESC')
               ->paginate(5);
    

    But this code takes all records from database. So you should paginate manually.

           $hackathons = Hackathon::leftJoin('hackathon_user','hackathon.id','=','hackathon_user.hackathon_id')
               ->selectRaw('hackathon.*, count(hackathon_user.hackathon_id) AS `count`')
               ->groupBy('hackathon.id')
               ->orderBy('count','DESC')
               ->skip(0)->take(5)->get();
    

    Referred from : https://stackoverflow.com/a/26384024/2186887

提交回复
热议问题