使用Zend_Db_Table_Abstract将WHERE子句分组

时间:2009-07-24 18:13:19

标签: zend-framework zend-db-table

有没有人知道如何将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@address.com') OR (client_email_alt = 'email@address.com')

但我需要它给我这个,OR语句被分组:

SELECT `clients`.* FROM `clients` WHERE (company_id = '1') AND ((client_email = 'email@address.com') OR (client_email_alt = 'email@address.com'))

5 个答案:

答案 0 :(得分:54)

为了实现这一目标,您必须在对where方法的单个调用中构建分组子句。

如果两个条件值相同,则可以执行以下操作:

$select->where('client_email = ? OR client_email_alt = ?', $client_email)

如果字符串中有多个占位符,则数据库适配器的quoteInto方法将使用提供的值替换所有占位符。

如果您需要为每个字段对OR分组不同的值,则必须手动引用这些值。它有点复杂:

$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 

答案 1 :(得分:6)

您可以使用getPart()获取WHERE语句,然后连接子查询。

$select->where('client_email = ?', $client_email)
       ->orWhere('client_email_alt = ?', $client_email);

$subquery = $select->getPart(Zend_Db_Select::WHERE);
$select ->reset(Zend_Db_Select::WHERE);
$select ->where('company_id = ?', $company_id)
        ->where(implode(' ',$subquery));

答案 2 :(得分:1)

对于Zend Framework Version 2,情况有所不同:

请参阅http://framework.zend.com/apidoc/2.2/classes/Zend.Db.Sql.Predicate.Predicate.html#nest

$table->select()
     ->where(['company_id'=> $company_id])
     ->nest
         ->where('client_email = ?', $client_email)
         ->or
         ->where('client_email_alt = ?', $client_email)
     ->unnest();

工作得很好,感觉比ZF1方法更清洁。

答案 3 :(得分:0)

首先,您可以生成子查询,然后获取“WHERE”部分并插入主查询

$subquery = $db->select();
$subquery->orWhere('a>10');
$subquery->orWhere('b<20');
etc..

$subquery = $subquery->getPart(Zend_Db_Select::WHERE);
$select->where(implode(' ',$subquery));

答案 4 :(得分:0)

我需要组合AND / OR语句,但有条件地包含OR语句,仅在某些情况下添加它们。这个解决方案是对我所做的改编,基于对已接受答案的小修改。

$sql = $table->select()
         ->where('company_id = ?', $company_id);

$orWhereClauses = [];
// We could add a conditional statement to add this statement
$orWhereClauses[] = $db->quoteInto('client_email = ?', $email1);
// Same applies to this statement
$orWhereClauses[] = $db->quoteInto('client_email_alt = ?', $email2);

$sql->where(implode(" OR ", $orWhereClauses));