Laravel Query Builder WHERE NOT IN
Asked Answered
F

2

8

I have the following sql query

SELECT * FROM exams WHERE exams.id NOT IN (SELECT examId FROM testresults)

how can I convert it into Laravel query builder format?

Thanks.

Frightened answered 6/2, 2015 at 8:25 Comment(0)
C
29

You can use whereNotIn with a closure:

$result = DB::table('exams')->whereNotIn('id', function($q){
    $q->select('examId')->from('testresults');
})->get();
Cheyenne answered 6/2, 2015 at 8:34 Comment(1)
do I still need to add ->get() at the end?Frightened
R
1

with Eloquent :

$result = Exams::whereNotIn('id', function($q){
        $q->select('examId')->from('testresults');
    })->get();
Romilly answered 13/10, 2020 at 7:34 Comment(1)
As this question has an accepted answer from 2015, it would be much more useful to anyone viewing this question if you could edit your answer and explain how your answer differs from the accepted answer and in which circumstances you believe it would be a better approach.Flori

© 2022 - 2024 — McMap. All rights reserved.