Ad

Order By Pivot Column

- 1 answer

I have two models, students and languages. Each student can speak n languages with a certain skill via pivot table student_language. For example Mike speaks English with a skill of 3 and german with a skill of 7.

Here is the student model:

class Student extends \Eloquent {
    public function languages()
    {
        return $this->belongsToMany('Language')->withPivot('skill');
    }
}

And here is the language model:

class Language extends \Eloquent {
    public function students()
    {
        return $this->belongsToMany('Student')->withPivot('quality');
    }    
}

How can I get a list of students that speaks a language, and sort them by their skill level? In Fluent it would be something like this, but I cannot use joins and need to write it in Eloquent:

$students = DB::table('students')
    ->join('student_language', 'students.id', '=', 'student_language.student_id')
    ->where('student_language.language_id', '=', '1')
    ->orderBy("student_user.skill", "desc")
    ->get();

Thank you for any inputs.

Edit: update

Ad

Answer

I haven't check this but you can try this

Student::with(['languages' => function($q) {
    $q->orderBy('pivot_skill', 'ASC');
}])->get();
Ad
source: stackoverflow.com
Ad