Question

I have a form with check boxes and I would like to create a query like:

SELECT * FROM table WHERE name = 'name' AND (option = 'check1' OR option = 'check2' OR option = 'check3')

The nested conditions will depend on what checkboxes the user selected.

The only way I know or can find examples on how to do nested conditions look like:

$select->where->nest
    ->equalTo('option', 'check1')
    ->or
    ->equalTo('option', 'check2')
    ->or
    ->equalTo('option', 'check3')
    ->unnest();

But this would only work with a static number of equalTo's inside the nest, when my case would have a variable amount. I would like to do something like this (where $filters is an array of checkbox values selected by user):

$select->where->StartNest();
foreach($filters['check'] as $check){
    $select->where->like('option', '%'.$check.'%');
    $select->where->or;
}
$select->where->StopNest();

Is anything like this possible? Or is there a better way to approach this problem?

Thank you very much for looking at the problem!

EDIT:

Here is how I ended up doing it. Seems a little hacky, but it is doing the job for now:

$strLiteral = '';
foreach($filters['check'] as $check){
    $strLiteral .= "options LIKE '%$check%' OR ";
}
$strLiteral = substr($strLiteral, 0, -4);  //remove the final ' OR' from string
$select->where->nest
    ->literal($strLiteral)
    ->unnest;
Was it helpful?

Solution 2

Here is how I ended up doing it. Seems a little hacky, but it is doing the job for now:

$strLiteral = '';
foreach($filters['check'] as $check){
    $strLiteral .= "options LIKE '%$check%' OR ";
}
$strLiteral = substr($strLiteral, 0, -4);  //remove the final ' OR' from string
$select->where->nest
    ->literal($strLiteral)
    ->unnest;

If anyone knows a better way to accomplish this, let me know. Thanks!

OTHER TIPS

Here is how I ended up doing it:

$p = new Predicate();
foreach($filters['check'] as $check) {
    $p->OR->like('option', '%'.$check.'%');
}
$select->where->addPredicates($p);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top