Laravel OrderBy relationship count

后端 未结 5 940
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条回答
  •  萌比男神i
    2020-11-28 07:08

    Edit: If using Laravel 5.2 or greater, use kJamesy's answer. It will likely perform a bit better because it's not going to need to load up all the participants and hackathons into memory, just the paginated hackathons and the count of participants for those hackathons.

    You should be able to use the Collection's sortBy() and count() methods to do this fairly easily.

    $hackathons = Hackathon::with('participants')->get()->sortBy(function($hackathon)
    {
        return $hackathon->participants->count();
    });
    

提交回复
热议问题