问题描述
我想在Zend_Db中生成这个复杂的WHERE子句:
I want to generate this complex WHERE clause in Zend_Db:
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代码:
I did figure out one method of making this work but I felt it was sort of 'cheating' by using PHP to combine the "OR" clauses first and then combine them using Zend_Db where() clause. PHP code:
$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工具而不是首先在PHP中组合来获取该复杂WHERE语句(实际上并不太复杂,只需添加一些括号)的官方"方法.
That produced what I was looking for. But I'm curious if there's an "official" way of getting that complex WHERE statement (which really isn't too complex, just adding some parenthesis) with using the Zend_Db tool, instead of combining it in PHP first.
干杯!
推荐答案
这将是为您提供指定括号的官方"方法(请参见 Zend_Db_Select
文档):
This would be the 'official' way to get you the parentheses as specified (see Example #20 in the Zend_Db_Select
documentation):
$a1 = 'one';
$a2 = 'two';
$select->from('product');
$select->where('status = ?', $status);
$select->where("attribute = $a1 OR attribute = $a2");
因此,由于您不知道自己提前拥有多少个属性,因此您所做的事情似乎很合理.
So, what you are doing does seem reasonable, given that you do not know how many attributes you have ahead of time.
这篇关于Zend_Db使用多个AND OR运算符的复杂WHERE子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!