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 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();
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With