Rob
Rob

Reputation: 164

Laravel orWhere giving unexpected result

I have a query.

  $bid_check        =     Bidders::where([

                                          'project_id'  =>    $id,

                                          'status'      =>    1,

                                          'active'      =>    1,

                                        ])

                                        ->orWhere([

                                                  'project_id'  =>    $id,

                                                  'status'      =>    2,

                                                  'active'      =>    1

                                                ])

                                ->first();

                                print_r($bid_check);die;

When I write it without orWhere it is showing no results which are okay, but when I write orWhere it gives me the first column of the database which is wrong. The condition in where and orWhere do not match with any of the columns in the DB. So, it should return empty, but it is returning the first column of DB. Why is it returning a value, has anyone faced the same issue?

Upvotes: 0

Views: 759

Answers (4)

madalinivascu
madalinivascu

Reputation: 32354

Better if you use a whereIn function

Bidders::where(['project_id'=>$id,'active'=>1])
         ->whereIn('status', [1,2])
         ->first();

i think the array in the orWhere is create as a list of or clauses not as a and clause so you will have or project_id = $id or active = 1 or status = 2

if the above is true then you should do the following

->orWhere(function($query) {
     return $query->where([
       'project_id'  =>    $id,
       'status'      =>    2,
       'active'      =>    1
    ]);
});

Upvotes: 2

user10186369
user10186369

Reputation:

You should try this:

$bid_check =     Bidders::where('active', 1)
                            ->where('project_id', $id)
                            ->where(function ($query) {
                                   $query->where('status', 1)->orWhere('status', 2);
                             })
                           ->first();

Upvotes: 0

Akshay Deshmukh
Akshay Deshmukh

Reputation: 1292

Try with below code.

 Bidders::where(function ($query) {
         $query->orWhere([  'project_id'  =>    $id
                            'active'      =>    1
                         ])
               ->orWhere('status', 1)
               ->orWhere('status', 3)
               ->orWhere('status', 2);
       })->get();

Upvotes: 0

J. Doe
J. Doe

Reputation: 1742

Try this:

Bidders::where('project_id', $id)
         ->where('active', 1)
         ->where(function ($query) {
             $query->where('status', 1)
                   ->orWhere('status', 2);
         })->first();

Upvotes: 2

Related Questions