php - Sort or order items with multiple relationships in laravel 5.1

947

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

quizzesid,name,body

multiple_choiceid,name,question

multiple_choice_quizid,multiple_choice_id,quiz_id

question_numbersid,quiz_id,question_id,question_number


Thequestion_number field in thequestion_numbers table is the field that I want to sort or order.

People are also looking for solutions to the problem: Dynamic class method name in php

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.