skip to Main Content

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.

2

Answers


  1. 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();
    
    Login or Signup to reply.
  2. option-1: another way is

    //Grade model with relation function 
    public function StudentMathLevel1()
    {
        return $this->belongsTo(Student::class)->where('level',1)->where('subject','math1');
    }
    

    usage in controller

    Grade::with('StudentMathLevel1')->orderBy('grade')->get();
    

    ==============================

    option-2: Further, you can also try the Scope functional approach

    //Grade model with relation function using 'scope'
    public function scopeStudentSpecificSubjectLevel($subject, $level)
    {
        return $this->belongsTo(Student::class)->where('level',$level)->where('subject',$subject);
    }
    

    usage in controller

    Grade::StudentSpecificSubjectLevel('math1',1)->orderBy('grade')->get();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search