Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel multiple where clauses within a loop

Pretty much I want the query to select all records of users that are 25 years old AND are either between 150-170cm OR 190-200cm.

I have this query written down below. However the problem is it keeps getting 25 year olds OR people who are 190-200cm instead of 25 year olds that are 150-170 OR 25 year olds that 190-200cm tall. How can I fix this? thanks

 $heightarray=array(array(150,170),array(190,200));
 $user->where('age',25);

   for($i=0;$i<count($heightarray);i++){
 if($i==0){
   $user->whereBetween('height',$heightarray[$i])
}else{
   $user->orWhereBetween('height',$heightarray[$i])
 }
 }
      $user->get();

Edit: I tried advanced wheres (http://laravel.com/docs/queries#advanced-wheres) and it doesn't work for me as I cannot pass the $heightarray parameter into the closure.

from laravel documentation

 DB::table('users')
        ->where('name', '=', 'John')
        ->orWhere(function($query)
        {
            $query->where('votes', '>', 100)
                  ->where('title', '<>', 'Admin');
        })
        ->get();
like image 802
user1424508 Avatar asked Oct 21 '13 03:10

user1424508


2 Answers

Like Jeemusu and the OP stated, you need to use advance wheres. But if you want to pass a variable to the closure function you need to make use of the "use" approach:

$heightarray = array(array(150,170),array(190,200));

DB::table('users')
  ->where('name', '=', 'John')
  ->orWhere(function($query) use ($heightarray){
    //...
  })
  ->get();
like image 126
FR6 Avatar answered Oct 16 '22 13:10

FR6


I found the answer. I need to include "use" in the closure to pass my $heightarray variable in. Once $heightarray is in then laravel's advance wheres work.

$heightarray=array(array(150,170),array(190,200));
  $user->where('age',25);

 $userprofile->Where(function($query) use ($heightarray) {

 for($i=0;$i<count($heightarray);i++){
 if($i==0){
 $user->whereBetween('height',$heightarray[$i])
 }else{
 $user->orWhereBetween('height',$heightarray[$i])
  }
}

 });

  $user->get();
like image 22
user1424508 Avatar answered Oct 16 '22 13:10

user1424508