Laravel Eloquent where field is X or null

后端 未结 3 1982
长发绾君心
长发绾君心 2021-01-31 13:29

I have a table like this:

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

Now I want to get all entries

相关标签:
3条回答
  • 2021-01-31 13:54

    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.

    0 讨论(0)
  • 2021-01-31 13:56

    You could merge two queries together:

    $merged = $query_one->merge($query_two);
    
    0 讨论(0)
  • 2021-01-31 14:06

    Using coalesce() converts null to 0:

    $query = Model::where('field1', 1)
        ->whereNull('field2')
        ->where(DB::raw('COALESCE(datefield_at,0)'), '<', $date)
    ;
    
    0 讨论(0)
提交回复
热议问题