使用 Zend_Db_Table_Abstract 对 WHERE 子句进行分组 [英] Grouping WHERE clauses with Zend_Db_Table_Abstract
问题描述
有谁知道用 Zend_Db 对 where 子句进行分组的方法?基本上我有这个查询
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);
这是给我的:
SELECT `clients`.* FROM `clients` WHERE (company_id = '1') AND (client_email = 'email@address.com') OR (client_email_alt = 'email@address.com')
但我需要它给我这个,OR 语句被分组:
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'))
推荐答案
为了实现这一点,您必须在对 where
方法的单个调用中构造分组子句.
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:
$select->where('client_email = ? OR client_email_alt = ?', $client_email)
如果字符串中有多个占位符,DB 适配器的 quoteInto
方法将用提供的值替换所有占位符.
If there are multiple placeholders within the string, the DB adapter's quoteInto
method will replace all placeholders with the provided value.
如果您需要为每个字段使用不同的值对 OR
进行分组,则必须手动引用这些值.有点复杂:
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:
$select->where(
$db->quoteInto('client_email = ?', $email1) . ' OR ' . $db->quoteInto('client_email_alt = ?', $email2)
); // $db is your instance of Zend_Db_Adapter_*
// You can get it from a Zend_Db_Table_Abstract
//subclass by calling its getAdapter() method
这篇关于使用 Zend_Db_Table_Abstract 对 WHERE 子句进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!