据我所知,whereNotExists应该排除所传递的闭包中的所有查询。然而,我得到了意想不到的结果。
我想要做的是把所有申请关闭的学生都送回去;学生不是家长设定的缺课或缺席。我得到的是一群空荡荡的学生。
我做错了什么?
$students = DB::table('rounds')
->where('rounds.bus_id', '=', $bus_id)
->join('rounds_students', 'rounds_students.round_id', 'rounds.id')
->whereNotExists(function ($query) {
$query->select(DB::raw(1))
->from('student_history')
->where('student_history.student_id', '=', 'rounds_students.student_id')
->where('student_history.activity_type', '=', 'absent')
->orWhere('student_history.activity_type', '=', 'absent-by-parent');
})
->join('students', 'students.id', 'rounds_students.student_id')
->select('students.name')
->get();
return $students;
发布于 2017-05-18 14:38:47
whereRaw()
或where(DB::raw('...'))
中使用原始表达式来定义NOT EXISTS
子句中的关联条件。否则,'rounds_students.student_id'
将作为字符串值传递,这不是您想要的。AND
s和OR
s在您的WHERE
条件下!你的错。将其改为whereIn
,使其更加简洁。此外,您也不需要在select(DB::RAW(1))
子句中真正使用EXISTS
。数据库优化器知道,它们不需要将任何结果集返回到外部查询。这可能有助于保持您的代码不臃肿。
试一试
$students = DB::table('rounds')
->select('students.name')
->join('rounds_students', 'rounds_students.round_id', 'rounds.id')
->join('students', 'students.id', 'rounds_students.student_id')
->where('rounds.bus_id', $bus_id)
->whereNotExists(function ($query) {
$query->from('student_history')
->whereRaw('student_history.student_id = rounds_students.student_id')
->whereIn('student_history.activity_type', ['absent', 'absent-by-parent']);
})
->get();
https://stackoverflow.com/questions/44048340
复制相似问题