Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Where and OrWhere

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?

like image 480
TheUnreal Avatar asked Nov 14 '25 16:11

TheUnreal


1 Answers

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();
like image 87
num8er Avatar answered Nov 17 '25 09:11

num8er



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!