簡體   English   中英

使用多個AND運算符的Zend_Db的復雜WHERE子句

[英]Complex WHERE clause with Zend_Db using multiple AND OR operators

我想在Zend_Db中生成這個復雜的WHERE子句:

SELECT * 
FROM 'products' 
WHERE 
    status = 'active' 
    AND 
    (
        attribute = 'one' 
        OR 
        attribute = 'two' 
        OR 
        [...]
    )
;

我試過這個:

$select->from('product');
$select->where('status = ?', $status);
$select->where('attribute = ?', $a1);
$select->orWhere('attribute = ?', $a2);

那產生了:

SELECT `product`.* 
FROM `product` 
WHERE 
    (status = 'active') 
    AND 
    (attribute = 'one') 
    OR 
    (attribute = 'two')
;

我確實找到了一種方法來完成這項工作,但我覺得通過先使用PHP組合“OR”子句然后使用Zend_Db where()子句將它們組合起來,這有點“作弊”。 PHP代碼:

$WHERE = array();
foreach($attributes as $a):
    #WHERE[] = "attribute = '" . $a . "'";
endforeach;
$WHERE = implode(' OR ', $WHERE);

$select->from('product');
$select->where('status = ?', $status);
$select->where($WHERE);

這產生了我想要的東西。 但我很好奇是否有一種“官方”的方式來獲取復雜的WHERE語句(實際上並不太復雜,只是添加一些括號)和Zend_Db工具,而不是先在PHP中組合它。

干杯!

這將是獲得指定括號的“官方”方式(參見Zend_Db_Select文檔中的示例#20):

$a1 = 'one';
$a2 = 'two';
$select->from('product');
$select->where('status = ?', $status);
$select->where("attribute = $a1 OR attribute = $a2");

所以,你所做的事情似乎是合理的,因為你不知道你提前有多少屬性。

如果使用所選答案,則需要記住在構造查詢之前引用值以防止SQL注入。

使用Zend Db Select創建查詢並引用值的另一個選項是在兩個階段中執行此操作:

/// we just use this select to create the "or wheres"
$select1->from('product');
foreach($attributes as $key => $a) {
    if ($key == 0) {
    /// we don't want "OR" for first one
        $select1->where("attribute = ?", $a);
    } else {
        $select1->orWhere("attribute = ?", $a);
    }   
}

/// now we construct main query
$select2->from('product');
$select2->where('status = ?', $status);
$select2->where(implode(' ', $select1->getPart('where')));

這樣Zend Db Select就可以完成所有的SQL生成。 一個老問題,但希望這個想法可能對有類似問題的人有用。

我使用這個解決方案,似乎按照需要工作。

$select->from('product');
$select->where('status = ?', $status);
$select->where('(attribute = ?', $a1);
$select->orWhere('attribute = ?)', $a2);

如果您的屬性是同一個表列,並且您想要檢查它是否等於多個值中的一個,那么您可以使用IN:

$select->from('product');
$select->where('status = ?', $status);
$select->where('attribute IN (?)', [$a1, $a2, ...]);

要么

$select->where('attribute IN (:someName)');
$select->setParameter('someName', [$a1, $a2, ...]);

否則我看不到上面的決定, "attribute = $a1 OR attribute = $a2"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM