Question:
I saw tutorials on the internet that the way you had to make an IS NULL
is as follows:
Remessa::where('campo', 'IS', DB::raw('NULL'))->get();
But I was wondering about this, because if an ORM is usually developed thinking about creating a way to query data that is compatible with all DBMSs.
Although it works, I believe that the form highlighted above is not essential.
With Eloquent
, is there any method (other than the one highlighted above) that I can do a where
doing the IS NULL
or IS NOT NULL
condition?
I think that this current way ends up getting repetitive.
Answer:
Yes, there are two methods; one you can use for IS NULL
and one for NOT NULL
.
examples follow:
For IS NULL
you can use
Remessa::whereNull('campo')->get();
You can also do it in a way, where you can pass multiple IS NULL
in a simpler way:
Remessa::where(['campo' => NULL, 'usuario_id' => NULL])->get();
e para NOT NULL
Remessa::whereNotNull('campo')->get();
To see the results that are generated by the queries, you can use the toSql
method at the end to test.
Remessa::where(['campo' => NULL])->toSql();
The output will be:
SELECT * FROM remessas where (campo IS NULL)