BlackPearl
BlackPearl

Reputation: 2775

Laravel: Proper way to use Where and orWhere in query

Currently running a query in Laravel but the expected output is not correct. So, it seems I still don't know the proper way to use where/orwhere. I have this two queries below;

QUERY 1 (a)

//total friends
    $user = Friend::select('friend_sender', 'friend_receiver')
                ->where('friend_sender', Input::get("user_id"))
                ->orwhere('friend_receiver', Input::get("user_id"))
                ->where('friendship_status','friends')->count(); 

QUERY 1 (b)

//total friends
    $user = Friend::select('friend_sender', 'friend_receiver')
                    ->where('friendship_status','friends')
                    ->where('friend_sender', Input::get("user_id"))
                    ->orwhere('friend_receiver', Input::get("user_id"))->count(); 

These two queries produces different results. QUERY 1 (a) result is 0, which is right in my own example and QUERY 1 (b) result is 1 which is wrong.

Now, I assumed that other WHEREs should come after the WHERE/orWHERE statements. I wrote another query but didn't get the required result.

$user = Friend::select('friend_sender', 'friend_receiver')
                ->where('friend_sender',Input::get("user_id"))
                ->orwhere('friend_receiver',Input::get("user_id"))
                ->where('sender_follow', 'yes')
                ->orwhere('receiver_follow', 'yes')
                ->where('friendship_status', 'friends')->count();   

My question is, how do I use WHERE/orWHERE properly?

Upvotes: 0

Views: 1246

Answers (2)

KyleK
KyleK

Reputation: 5056

See this example from the documentation:

DB::table('users')
        ->where('name', '=', 'John')
        ->orWhere(function($query)
        {
            $query->where('votes', '>', 100)
                  ->where('title', '<>', 'Admin');
        })
        ->get();

The closure will tell: AND first, then OR condition.

Upvotes: 1

Ceeee
Ceeee

Reputation: 1442

read about Operator precedence of mysql: http://dev.mysql.com/doc/refman/5.0/en/operator-precedence.html

in you example, the first query is same with something like:

select 
   columns 
from 
   table 
where
   column1 = value1 
or
   (column2 = value2 and column3 = value3)

while the other query is same with something like:

select 
   columns 
from 
   table 
where
   (column3 = value3 and column1 = value1) 
or
   column2 = value2

the 'AND' would be first to be evaluated by the sql thats why it yields different result

Upvotes: 2

Related Questions