Reputation: 88
Is it possible to make a select like the following example using Eloquent ORM.
select .. where ... AND ( ( ... AND ...) OR ( ... AND ... ))
Here is my "workaround" :
$tasks1=$user->Tasks()
->WhereBetween('start_date',array($start,$end))
->where('deleted',0)
->where('dated','=',1)
->where('status','=',$state)
->get();
$tasks2=$user->Tasks()
->WhereBetween('due_date',array($start,$end))
->where('deleted',0)
->where('dated','=',1)
->where('status','=',$state)
->get();
$tasks3=$user->Tasks()
->where('start_date','<',$start)
->where('due_date','>',$end)
->where('deleted',0)
->where('dated','=',1)
->where('status','=',$state)
->get();
$tasks = $tasks1->merge($tasks2);
$tasks = $tasks->merge($tasks3);
As you can see I am just running multiple queries using AND only, while merging them simulates the OR.
Any ideas? thanks.
Upvotes: 1
Views: 351
Reputation: 5774
You can indeed perform grouped and
or
queries using Laravels Eloquent:
$tasks = Tasks::whereBetween('start_date', array($start,$end))
->where(function($query)
{
->where(function($q)
{
$q->where('column_a', 'foo')
->where('column_b', 'bar');
})
->orWhere(function($q)
{
$q->where('column_c', 'foo')
->where('column_d', 'bar');
})
})
->get();
This would produce a query like you were describing:
SELECT ... WHERE ... AND ((... AND ...) OR (... AND ...))
For more info about advanced where statements in Laravel check the docs here: http://laravel.com/docs/4.2/queries#advanced-wheres
Upvotes: 3