Reputation: 589
I have a SQL sentence like this
select count(*) as aggregate from books inner join apartments on apartment_id = apartments.id
where (date_ini <= ? and date_fin > ?)
or (date_ini < ? and date_fin >= ?)
or (date_ini >= ? and date_fin <= ?)
I already did the sentence in laravel
$searchResult=DB::table('books')->join('apartments', 'apartment_id', '=', 'apartments.id')
->where(function($query){
$query->where('date_ini', '<=', Input::get( 'desdeGet' ))
->where('date_fin','>', Input::get( 'desdeGet' ));
})
->orwhere(function($query){
$query ->where('date_ini', '<', Input::get( 'hastaGet' ))
->where('date_fin', '>=', Input::get( 'hastaGet' ));
})->orwhere(function($query){
$query->where('date_ini', '>=', Input::get( 'desdeGet' ))
->where('date_fin', '<=', Input::get( 'hastaGet' ));
})->paginate(2);
Everything is ok but I need to add one more AND condition at the end of the clause, I realized that I need to enclose all the previous clause like this and add the last AND at the end
select count(*) as aggregate from books inner join apartments on apartment_id = apartments.id
where (
(date_ini <= ? and date_fin > ?)
or (date_ini < ? and date_fin >= ?)
or (date_ini >= ? and date_fin <= ?)
)and col1=?
I dont know how to enclose all that in query builder, any advice?
Thanks.
Upvotes: 1
Views: 1628
Reputation: 23972
Put all your boolean conditions in a nested where clause and add the first where clause that will act as an AND, like:
$searchResult=DB::table('books')->join('apartments', 'apartment_id', '=', 'apartments.id')
->where('col1','=','foobar')
->where(function($queryContainer){
$queryContainer->where(function($query){
$query->where('date_ini', '<=', Input::get( 'desdeGet' ))
->where('date_fin','>', Input::get( 'desdeGet' ));
})
->orwhere(function($query){
$query ->where('date_ini', '<', Input::get( 'hastaGet' ))
->where('date_fin', '>=', Input::get( 'hastaGet' ));
})
->orwhere(function($query){
$query->where('date_ini', '>=', Input::get( 'desdeGet' ))
->where('date_fin', '<=', Input::get( 'hastaGet' ));
});
})
->paginate(2);
Upvotes: 2