使用 Zend_Db_Table_Abstract 对 WHERE 子句进行分组
有谁知道如何将 where 子句与 Zend_Db 分组? 基本上我有这个查询
$sql = $table->select()
->where('company_id = ?', $company_id)
->where('client_email = ?', $client_email)
->orWhere('client_email_alt = ?', $client_email);
,它给了我这个:
SELECT `clients`.* FROM `clients` WHERE (company_id = '1') AND (client_email = '[email protected]') OR (client_email_alt = '[email protected]')
但我需要它给我这个,其中 OR 语句分组:
SELECT `clients`.* FROM `clients` WHERE (company_id = '1') AND ((client_email = '[email protected]') OR (client_email_alt = '[email protected]'))
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 protected]') OR (client_email_alt = '[email protected]')
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 protected]') OR (client_email_alt = '[email protected]'))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
为了实现此目的,您必须在对
where
方法的单次调用中构造分组子句。如果两个条件值相同,您可以这样做:
如果字符串中有多个占位符,数据库适配器的
quoteInto
方法将用提供的值替换所有占位符。如果您需要将每个字段具有不同值的
OR
分组,则必须手动引用这些值。 这有点复杂: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:您可以使用
getPart()
来获取WHERE语句,然后连接子查询。You can use
getPart()
to get WHERE statement and then connect sub-queries.对于 Zend Framework 版本 2,情况略有不同:
请参阅 http://framework.zend.com/apidoc/2.2/classes/Zend.Db.Sql.Predicate.Predicate.html#nest
工作正常,感觉比 ZF1 方法干净得多。
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.
我需要组合 AND/OR 语句,但有条件地包含 OR 语句,仅在某些情况下添加它们。 该解决方案是对我所做的事情的改编,基于对已接受答案的微小修改。
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.
首先,您可以生成子查询,然后获取“WHERE”部分并插入到主查询中
In first you can generate subquery, then get "WHERE" part and insert into main query