在laravel 5.1中对具有多个关系的项目进行排序或排序

时间:2017-10-10 07:48:27

标签: php laravel-5

我正在使用多种关系并使用eager loading。我现在拥有三个表格(quizzesmultiple_choicequestion_numbers),我想使用multiple_choice表格对question_numbers字段进行排序{ {1}}。我怎样才能做到这一点?请参阅下面的代码:

question_number

我尝试了评论部分,但没有发生。

使用dd()

进行更新

使用 $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'); 后,结果为:

dd()

UPDATE2

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
    }
  ]
}

更新3
数据库

#relations: array:2 [▼ "pivot" => Pivot {#426 ▶} "question_numbers" => Collection {#452 ▼ #items: array:1 [▼ 0 => Quiz {#449 ▶} ] } ] - quizzesidname

body - multiple_choiceidname

question - multiple_choice_quizidmultiple_choice_id

quiz_id - question_numbersidquiz_idquestion_id


question_number表中的question_number字段是我要排序或订购的字段。

0 个答案:

没有答案