Search code examples
phplaravel

Laravel: how to sort base on relationship column


We have Student Model. The Student Model hasMany relationship with Grade Model

Here are columns:

Student - id, level, name, status

Grade - id, student_id, subject, grade, status

Basically what I'm trying to do is query all the first level students that took math1 subject and sort it with grades

Here is my code so far:

$r = Student::where("level", 1)
           ->whereRelation('grades', 'subject', 'math1')
           ->get();

This works on filtering the first level students with math1 subject but my question is how can i sort base on relatioship grade column?

Thanks in advance.


Solution

  • My first thought was that I'd actually reverse this, if your main interest is the grades. When you know that you want to list all Students taking the math1 class, you could do something like this:

    Grade::with('Student')
        ->whereSubject('math1')
        ->whereHas('Student', fn($query) => $query->whereLevel(1))
        ->orderBy('grade')
        ->get();