gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-28 23:52:28 25 4
gpt4 key购买 nike

我想在 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);

这产生了我正在寻找的东西。但我很好奇是否有一种“官方”方式通过使用 Zend_Db 工具来获得复杂的 WHERE 语句(实际上并不太复杂,只是添加一些括号),而不是先在 PHP 中组合它。

干杯!

最佳答案

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

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

因此,鉴于您事先不知道自己拥有多少属性,因此您所做的似乎是合理的。

关于php - Zend_Db 使用多个 AND OR 运算符的复杂 WHERE 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4382602/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com