我试图找出如何在eloquent中创建以下查询:
SELECT *
FROM `pvp_battles`
WHERE (player1_id = 2 || player2_id =2) && winner !=2
2是玩家ID。这就是我所做的:
$profile->loses = PvpBattle::where('player1_id',$profile->id)
->orWhere('player2_id',$profile->id)
->where('winner','!=',$profile->id)->count();
可悲的是,它显示计数是49而它是25。 怎么了?
答案 0 :(得分:2)
以下是修复:
$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();
或:
$profile->loses = PvpBattle::where(DB::raw($profile->id.' IN (`player1_id`, `player2_id`)'))
->where('winner', '!=', $profile->id)->count();
答案 1 :(得分:2)
怎么样?
$profile->loses = PvpBattle::where(function($query) use ($profile){
$query->where('player2_id', '=', $profile->id)
->orWhere('player1_id', '=', $profile->id);
})
->where('winner','!=',$profile->id)->count();