简体   繁体   中英

Stuck at Laravel query

Trying to do a query in controller.

I have two tables in database:

students: id,name, surname,gender  
student_marks: id,student_id,year_id, subject_id, mark_id ... 

What I want is to count all the marks of students that their gender is female or male.

 $girls = StudentMarks::where('student_id','=',Student::where('gender','female')->value('id'))->count();

But nothing shows up.

If you have your relations correct it would be something like this:

$girls = StudentMark::whereHas('student', function($q) {
    $q->where('gender', 'female');
})->count();

Where students is the relation function in studentMark. Every model should be singleton.

You need to study on Laravel polymorphism. In your case, you need to make use of belongsTo and hasMany objects in this way.

In your Student model, add the following function

public function students_marks(){
  return $this->hasMany(StudentMark::class);
}

In your StudentMark model, add the following function

public function student(){
   return $this->belongsTo(Student::class, 'student_id', 'id');
}

While querying, use the whereHas clause to make your query as below

$student_marks = StudentMark::with('student')
->whereHas('student', function($student){
   $student->where('gender', 'female');
})->get()->count();

This should give you the count. For your own knowledge read more on Laravel Eloquent EagerLoading .

What you can do is go to Student model and define protected $withCount=['studnet_marks']

this will eagerload count of student_marks on Student model all the time.

So when you fetch a student you will have a student_count attribute that will contain count of student_marks .

Then your query should look something like :

 Student::whereHas('student_marks')->groupBy('gender')->get();

Basically get all the students that they have a student_mark and since we defined withCount in students model it will load a new attribute student_mark_count wich is count of student marks for each student.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM