简体   繁体   中英

How to select from a table based on another table's values Eloquent?

I am trying to get the data on some students that are still active. Even tho I have data from inactive students in the same table.

This is the StudentAttendance

在此处输入图片说明

This is the StudentClass

在此处输入图片说明

This is the Eloquent query that I came up with:

        StudentAttendance::
          select('student_classes.active', 'student_attendances.student_id', 'student_attendances.classroom_id', 'classrooms.classroom', 'attendance_rules.option')
        ->join('classrooms', 'classrooms.id', '=', 'student_attendances.classroom_id')
        ->join('attendance_rules','attendance_rules.id', '=', 'student_attendances.attendance_id')
        ->join('student_classes', 'student_attendances.student_id', '=', 'student_classes.student_id')
        ->where('attendance_date', date("Y-m-d"))        
        ->orderBy('classrooms.classroom', 'ASC')
        ->get();

SQL:

select `student_classes`.`active`, `student_attendances`.`student_id`, `student_attendances`.`classroom_id`, `classrooms`.`classroom`, `attendance_rules`.`option` 
from `student_attendances` 
inner join `classrooms` on `classrooms`.`id` = `student_attendances`.`classroom_id` 
inner join `attendance_rules` on `attendance_rules`.`id` = `student_attendances`.`attendance_id` 
inner join `student_classes` on `student_attendances`.`student_id` = `student_classes`.`student_id` 
where `attendance_date` = '2020-02-11' 
order by `classrooms`.`classroom` asc

Now my Eloquent query results into this:

在此处输入图片说明

As you can see the student_id 22 with the classroom_id of 2 is inactive but it appears to be inactive once and the rest active. If I remove the student_classes join I won't get all the repeated results.

The goal is to display all the attendances of today where the student is active (active=1) in the StudentClass even if I query in the StudentAttendance.

You will want to scope your join to student_classes to only look at active records.

You can do this by using a callback in your join method:

->join('student_classes', function ($join) {
    $join->on('student_attendances.student_id', '=', 'student_classes.student_id')
        ->on('student_classes.classroom_id', '=', 'student_attendances.classroom_id')
        ->where('student_classes.active', 1);
})

This is covered under the 'Advanced Join Clauses' in the Query Builder docs - https://laravel.com/docs/5.8/queries#joins

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