問題描述
我想在 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 工具來獲得復雜的 WHERE 語句(這真的不是太復雜,只是添加了一些括號),而不是先在 PHP 中組合它.
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 的復雜 WHERE 子句使用多個 AND OR 運算符的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!