Does anyone know of a way to group where clauses with Zend_Db? Basically I have this query
$sql = $table->select()
->where('company_id = ?', $company_id)
->where('client_email = ?', $client_email)
->orWhere('client_email_alt = ?', $client_email);
Which is giving me this:
SELECT `clients`.* FROM `clients` WHERE (company_id = '1') AND (client_email = 'email@address.com') OR (client_email_alt = 'email@address.com')
But I need it to give me this, where the OR statement is grouped:
SELECT `clients`.* FROM `clients` WHERE (company_id = '1') AND ((client_email = 'email@address.com') OR (client_email_alt = 'email@address.com'))
In first you can generate subquery, then get "WHERE" part and insert into main query
You can use
getPart()
to get WHERE statement and then connect sub-queries.In order to achieve this, you have to construct the grouped clause within a single call to the
where
method.If both values of conditions are the same, you can do this:
If there are multiple placeholders within the string, the DB adapter's
quoteInto
method will replace all placeholders with the provided value.If you need to group an
OR
with different values for each field, you have to manually quote the values. It's a bit more complex:I needed to combine AND/OR statements but including OR statements conditionally, adding them only in some cases. This solution is an adaptation of what I did, based on small modifications of the accepted answer.
For Zend Framework Version 2, things differ a bit:
See http://framework.zend.com/apidoc/2.2/classes/Zend.Db.Sql.Predicate.Predicate.html#nest
works fine and feels much cleaner than the ZF1 methods.