php - Sort pagniation by relationship count -


i want sort question amount of answers (one many relationship). orderby works columns, in case need sort value.

select   answers.question_id,   count(*) counter answers, questions answers.id = questions.id question.year > 2014 group answers.question_id order `counter` desc 

how can use laravel's pagnation here?

$questions->where('year', '>', 2014)     ->paginate(10) 

will pagnation, not sorting results.

sortby no solution, because need results, sorting them , picking 10. it's huge time waste.

you can make use of power of collections !
assusming have correctly set models.

$questions = question::with('answers')->get()->sortby(function($question) {     return $question->answers->count(); }); 

will return collection of questions sorted number of answers. can manually build paginator object (since paginate method can used on eloquent objects) :

$questions = new illuminate\pagination\paginator($questions, 10); // 10 being number of results per page. 

Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -