C
C
chelkaz2016-03-23 19:03:11
Laravel
chelkaz, 2016-03-23 19:03:11

How to make sorting sort on related table?

Now sorting by table id Question

$ArrQuest = Question::with('user', 'file', 'answer')->orderBy('id','desc')->paginate(15);

Is it possible to sort by the number of rows in the linked table? answer
I looked everywhere and did not find a single working solution.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrzej Wielski, 2016-03-25
@wielski

Something like this.
I threw an idea, I hope you figure it out yourself. Didn't test.

$Question = new Question;
$ArrQuest = Question::with('user', 'file', 'answer');

$Relation = $Question-> answer();
$Table = $Question->getRelated()->getTable();

$ArrQuest = $ArrQuest->join($Table, $Relation->getQualifiedForeignKey(), '=', $Relation->getQualifiedOtherKeyName())->orderBy(DB::raw("count(`{$Table}`.`id`)"), 'asc')->paginate(15);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question