Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent where field is X or null

I have a table like this:

table - field1: tinyint - field2: varchar (nullable) - datefield: timestamp (nullable) 

Now I want to get all entries where field1 is 1, field2 is null and where datefield is smaller than X or null. I already tried something like this:

$query = Model::where('field1', 1)             ->whereNull('field2')             ->where('datefield', '<', $date)             ->orWhereNull('datefield'); 

but thats not working. I always get every entry where datefield is null. It doesn't matter what the other fields are. I also tried to split it in 2 queries: First get every row where datefield is smaller than X or null and then (based on it) get every field where field1 is 1 and field2 is null.

The result was the same. Any idea how to do this?

like image 506
festie Avatar asked Apr 02 '16 09:04

festie


People also ask

Is null in WHERE clause in Laravel?

you can easily use it with laravel 6, laravel 7, laravel 8 and laravel 9 application. whereNull() will help you to getting data with null values from database. whereNotNull() will help you to getting data with not null values from database.

IS NOT NULL in Laravel eloquent?

Check if not null: whereNotNullSELECT * FROM users WHERE last_name IS NOT NULL; The equivalent to the IS NOT NULL condition in Laravel Eloquent is the whereNotNull method, which allows you to verify if a specific column's value is not NULL .

IS NULL check in Laravel?

You can check if the column value of a record is null or not in laravel using whereNotNull() and exists() method. exists() method returns false if the column value of a record in the table is null and it returns true if column value is not null.


2 Answers

It sounds like you need to make use of advanced where clauses.

Given that search in field1 and field2 is constant we will leave them as is, but we are going to adjust your search in datefield a little.

Try this:

$query = Model::where('field1', 1)     ->whereNull('field2')     ->where(function ($query) {         $query->where('datefield', '<', $date)             ->orWhereNull('datefield');     } ); 

If you ever need to debug a query and see why it isn't working, it can help to see what SQL it is actually executing. You can chain ->toSql() to the end of your eloquent query to generate the SQL.

like image 56
James Avatar answered Sep 18 '22 00:09

James


You could merge two queries together:

$merged = $query_one->merge($query_two); 
like image 36
kaleazy Avatar answered Sep 20 '22 00:09

kaleazy