据我了解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;
答案 0 :(得分:1)
whereRaw()
或where(DB::raw('...'))
的原始表达式来定义NOT EXISTS
子句中的相关条件。否则'rounds_students.student_id'
将作为字符串值传递,这不是您想要的。AND
条件中的OR
和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();