skip to Main Content

Is it possible to make eloquent generate a query with a WHERE clause precisely like the example in the title?

The closest I got was with Where() and orWhere(), but that outputs

(column_1 IS NOT NULL OR column_2 IS NOT NULL),

which gives different results than the query in the title!

Can someone also explain why these two WHERE clauses give different results?

2

Answers


  1. Chosen as BEST ANSWER

    As @Andrew pointed out in the comment to op, I incorrectly assumed that query

    WHERE (column_1 OR column_2 IS NOT NULL)
    

    checks both columns for null value, and returns all results where eirther column_1, column_2 or both are not null.

    The query in fact checks column_1 for true/false, and column_2 for null, and returns results where column_1 is true or column_2 is not null or both.

    Eloquent code that outputs a query like that is:

    $query = DB::table('your_table')
        ->where('column_1', true)
        ->orWhereNotNull('column_2')
    

    Edit: You should note if you have multiple where clauses, and to make eloquent output the query exactly as in the question (with parantheses), you must wrap in a closure like this:

    $query = DB::table('your_table')
        ->where(function (Builder $q) {
            $q->where('column_1 ', true)
            ->orWhereNotNull('datumPrenosa');
            })
        ->where(...
    

  2. Use a where closure on Eloquent.

    $results = 
    YOUR_MODEL::where(function($query) {
         $query->whereNotNull('column_1')
             ->orWhereNotNull('column_2');
        })->get();
    

    This will generate a query with a WHERE clause that looks like (column_1 IS NOT NULL OR column_2 IS NOT NULL).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search