Search code examples
mongodblaravellumenjenssegers-mongodb

Fix Mongo query in Lumen


I have a query in the lumen. But it does not work. The query is :

return Order::whereBetween('source_longitude', [$minLon_try_one, $maxLon_try_one])
        ->whereBetween('source_latitude',[51.365807806703,51.454384193297])
        ->where('status','=','pending')
        ->where('created_at','<=', 2016-04-07 12:00:35)
        ->where('created_at','>=', 2016-04-07 11:55:35)
        ->orWhere(function($query)
        {
                    $query->whereBetween('source_longitude', [51.321519613407, 51.498672386593])
                    ->whereBetween('source_latitude',[35.612195271526,35.756086728473])
                    ->where('status','=','pending')
                    ->where('created_at','<=',2016-04-07 11:55:35)
                    ->where('created_at','>=',2016-04-07 11:50:35);
        }
        )->get();

But when I remove orWhere function from the query I get expected result


Solution

  • You probably using orWhere a little bit wrong. You need to put where to another where to execute query properly. What You are doing now is something like that where a is 1 and b is 2 or (c is 3 and d is 4), but I believe, You want to do something like that where (a is 1 and b is 2) or (c is 3 and d is 4)
    Try this one:

        return Order::where(function ($query) {
            $query->whereBetween('source_longitude', [$minLon_try_one, $maxLon_try_one])
                ->whereBetween('source_latitude', [51.365807806703, 51.454384193297])
                ->where('status', '=', 'pending')
                ->where('created_at', '<=', '2016-04-07 12:00:35')
                ->where('created_at', '>=', '2016-04-07 11:55:35');
        })->orWhere(function ($query) {
            $query->whereBetween('source_longitude', [51.321519613407, 51.498672386593])
                ->whereBetween('source_latitude', [35.612195271526, 35.756086728473])
                ->where('status', '=', 'pending')
                ->where('created_at', '<=', '2016-04-07 11:55:35')
                ->where('created_at', '>=', '2016-04-07 11:50:35');
        })->get();