2017-05-18 1 views
0

어디 까지나 NotExists를 이해하면 전달 된 Closure 내의 모든 쿼리가 제외되어야합니다. 그러나 예상치 못한 결과가 나타납니다.Laravel 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

보십시오. 여기에서는 전혀 그렇게하지 않습니다. – apokryfos

+0

@apokryfos 이미 그랬지만 질문에서 언급하는 것을 잊어 버렸습니다. 질문을 업데이트했습니다. 나는 여전히 빈 $ students 배열을 가지고있다. – WingsOfAltair

답변

1
  1. 당신은 NOT EXISTS 절에 상관 조건을 정의 whereRaw() 또는 where(DB::raw('...'))와 원시 표현을 사용해야합니다. 그렇지 않으면 'rounds_students.student_id'이 원하는 값이 아닌 문자열 값으로 전달됩니다.
  2. WHERE 조건에서 ANDOR을주의하십시오! 너의 말이 틀렸다. 더 간결하게하기 위해 whereIn으로 변경했습니다.

또한 select(DB::RAW(1))EXISTS 절에 실제로 사용할 필요가 없습니다. 데이터베이스 최적화 프로그램은 외부 쿼리에 결과 집합을 반환 할 필요가 없음을 알고 있습니다. 이렇게하면 코드가 덜 부풀어 오르는 데 도움이 될 수 있습니다.

는 일반적으로`하위 쿼리가 외부 쿼리의 일부 요소를 사용 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();