php - Sort or order items with multiple relationships in laravel 5.1
I'm using multiple relationship and useseager loading
. What I have now are three tables (quizzes
,multiple_choice
,question_numbers
), and I want to sort themultiple_choice
using thequestion_numbers
table with the fieldquestion_number
. How can I do that? Please see my code below:
$undeleted = function($query){
return $query->where('deleted', 0);
};
$quiz = Quiz::with([
'multiple_choices.question_numbers' => $undeleted
])->find($id);
$quiz_items = collect($quiz->multiple_choices);
//$quiz_items = $quiz_items->sortBy('question_number');
I tried the commented part, but nothings happen.
Update with dd()
After I useddd()
, the result is:
Collection {#478 ▼
#items: array:13 [▼
0 => MultipleChoice {#427 ▼
#table: "multiple_choice"
#fillable: array:6 [▶]
#connection: null
#primaryKey: "id"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:9 [▼
"id" => 1
"name" => "My name"
"question" => "the question body"
"created_at" => "2017-06-06 00:00:00"
"updated_at" => "2017-10-07 18:34:36"
]
#original: array:13 [▶]
#relations: array:2 [▶]
#hidden: []
#visible: []
#appends: []
#guarded: array:1 [▶]
#dates: []
#dateFormat: null
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
+wasRecentlyCreated: false
}
]
}
Update2
#relations: array:2 [▼
"pivot" => Pivot {#426 ▶}
"question_numbers" => Collection {#452 ▼
#items: array:1 [▼
0 => Quiz {#449 ▶}
]
}
]
Update 3
databases
quizzes
—id
,name
,body
multiple_choice
—id
,name
,question
multiple_choice_quiz
—id
,multiple_choice_id
,quiz_id
question_numbers
—id
,quiz_id
,question_id
,question_number
Thequestion_number
field in thequestion_numbers
table is the field that I want to sort or order.