Eloquent eager load Order by

后端 未结 7 2151
花落未央
花落未央 2020-11-27 13:56

I have problem with eloquent query. I am using eager loading (one to one Relationship) to get \'student\' With the \'exam\', Using the code

7条回答
  •  旧时难觅i
    2020-11-27 14:42

    If you ALWAYS want it sorted by exam result, you can add the sortBy call directly in the relationship function on the model.

    public function exam() {
      return this->hasMany(Exam::class)->orderBy('result');
    }
    

    (credit for this answer goes to pfriendly - he answered it here: How to sort an Eloquent subquery)

提交回复
热议问题