使用多个AND运算符的Zend_Db的复杂WHERE子句

jmb*_*cci 15 php sql zend-framework zend-db

我想在Zend_Db中生成这个复杂的WHERE子句:

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

我试过这个:

$select->from('product');
$select->where('status = ?', $status);
$select->where('attribute = ?', $a1);
$select->orWhere('attribute = ?', $a2);
Run Code Online (Sandbox Code Playgroud)

那产生了:

SELECT `product`.* 
FROM `product` 
WHERE 
    (status = 'active') 
    AND 
    (attribute = 'one') 
    OR 
    (attribute = 'two')
;
Run Code Online (Sandbox Code Playgroud)

我确实找到了一种方法来完成这项工作,但我觉得通过先使用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);
Run Code Online (Sandbox Code Playgroud)

这产生了我想要的东西.但我很好奇是否有一种"官方"的方式来获取复杂的WHERE语句(实际上并不太复杂,只是添加一些括号)和Zend_Db工具,而不是先在PHP中组合它.

干杯!

kar*_*m79 22

这将是获得指定括号的"官方"方式(参见Zend_Db_Select文档中的示例#20 ):

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

所以,你所做的事情似乎是合理的,因为你不知道你提前有多少属性.


小智 5

如果使用所选答案,您需要记住在构造查询之前引用这些值以防止 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')));
Run Code Online (Sandbox Code Playgroud)

这样 Zend Db Select 就会生成所有 SQL。这是一个老问题,但希望这个想法对有类似问题的人有用。