Reputation: 24472
I am trying to figure out how to create the following query in eloquent:
SELECT *
FROM `pvp_battles`
WHERE (player1_id = 2 || player2_id =2) && winner !=2
2 is the player id. This is what I did:
$profile->loses = PvpBattle::where('player1_id',$profile->id)
->orWhere('player2_id',$profile->id)
->where('winner','!=',$profile->id)->count();
Sadly it shows that the count is 49 while it's 25. What's wrong?
Upvotes: 4
Views: 10632
Reputation: 46
You were wrong in evaluating OR and AND conditions. If the values are one by one the logical is that first evaluates AND and the OR. Your algorithm must be (Test1 OR Test 2) AND Test 3. If they are alltogether Test1 OR Test 2 AND Test 3 the logic first tests Test2 AND Test3 then makes an OR with Test 1.
The right codes needs a "closure function":
$profile->loses = PvpBattle::where(function($q) use($profile) { return $q
->where('player1_id', $profile->id)
->orWhere('player2_id', $profile->id); }) ->where('winner', '!=', $profile->id)->count();
Upvotes: 0
Reputation: 19372
Here is the fix:
$profile->loses = PvpBattle::where(function($q) use($profile) {
return $q
->where('player1_id', $profile->id)
->orWhere('player2_id', $profile->id);
})->where('winner', '!=', $profile->id)->count();
or:
$profile->loses = PvpBattle::where(DB::raw($profile->id.' IN (`player1_id`, `player2_id`)'))
->where('winner', '!=', $profile->id)->count();
Upvotes: 5
Reputation: 136
how about?
$profile->loses = PvpBattle::where(function($query) use ($profile){
$query->where('player2_id', '=', $profile->id)
->orWhere('player1_id', '=', $profile->id);
})
->where('winner','!=',$profile->id)->count();
Upvotes: 2