Uncoke
Uncoke

Reputation: 1902

Laravel OrWhere having two conditions is not so obvious

Why in Eloquent a simple query as this one is not working?

$matches = DB::table("matches")
   ->where(["team_a"=> $request->tid, "match_tipo"=>3])
   ->orWhere(["team_a"=> $request->tid, "match_tipo"=>3])
   ->first();

According to with other examples here on Stackoverflow, I should use a query in Where like:

$matches = DB::table("matches")
 ->where(["match_tipo"=>3])
 ->where(function($query, $request) {
      $query->where('team_h',$request->tid)
            ->orWhere('team_a',$request->tid);
      })
->first();

But I should pass a second parameter ($request).

How is the simplest way to do this query?

Upvotes: 2

Views: 341

Answers (3)

Yasin Patel
Yasin Patel

Reputation: 5731

Try this query :

$matches = DB::table("matches")
   ->where('match_tipo',3)
   ->whereRaw('team_a = "'.$request->tid.'" OR team_h = "'.$request->tid.'"')
   ->first();

Upvotes: 0

ManojKiran
ManojKiran

Reputation: 6341

while using the Callback or Closure as the where function Parameter you will only the one argument which is Current Object

Methods Can used to Pass the $request

Method One

$matches = DB::table("matches")
 ->where(["match_tipo"=>3])
 ->where(function($query) use ($request) {
      $query->where('team_h',$request->tid)
            ->orWhere('team_a',$request->tid);
      })
->first();

Method Two

$matches = DB::table("matches")
    ->where('match_tipo','=',3)
    ->when($request->tid,function($query) use ($request) {
        return $query->where('team_h',$request->tid)
              ->orWhere('team_a',$request->tid);
        })
   ->first();

Upvotes: 0

Dilip Hirapara
Dilip Hirapara

Reputation: 15296

You can make this as like this.

->where(["match_tipo"=>3]) this will be ->where("match_tipo",3) and use($tid) after query.

$tid = $request->tid; 
$matches = DB::table("matches")
 ->where("match_tipo",3)
 ->where(function($query) use($tid) {
      $query->where('team_h',$tid)
            ->orWhere('team_a',$tid);
      })
->get();

Upvotes: 2

Related Questions