TheUnreal
TheUnreal

Reputation: 24462

Laravel Query builder - OrWhere + Where

I have the following query:

public function getPvpBattle()
    {
        $battle = PvpBattle::where('player1_id','=',$this->id)
        ->orWhere('player2_id', '=', $this->id)
        ->where('mode','!=','FINISH')
        ->first();
        if ($battle) return $battle;
        else
            return false;
    }

For some reasons, it doesn't work as excepted on every user, and it returns different rows for player1_id and player2_id which supposed to be in the same battle.

What's wrong in this query and how I can make it to work and reutrn the same result for player1_id and player2_id which belongs to the same row?

Upvotes: 2

Views: 7014

Answers (1)

krisanalfa
krisanalfa

Reputation: 6428

How about using this query?

$id = $this->id;

$battle = PvpBattle::where('mode', '!=', 'FINISH')
    ->where(function ($query) use ($id) {
        $query->where('player1_id', '=' , $id)
            ->orWhere('player2_id', '=', $id);
    })
    ->first();

Read more about advance query here.

Upvotes: 9

Related Questions