这种方法,已作为官方例子Zend框架的复杂WHERE语句
- >在哪里( “价格< $ minimumPrice或价格> $ maximumPrice”) 是这种方法安全吗?
想把它写成 - >在哪里( “价格<或价格>?”,$ minimumPrice,$ maximumPrice) 是否有任何poissibility?
,我不能将其分割成2,其中陈述,因为计划写查询 - >其中( “1或2”) - >其中( “3 OR 4”)
这种方法,已作为官方例子Zend框架的复杂WHERE语句
- >在哪里( “价格< $ minimumPrice或价格> $ maximumPrice”) 是这种方法安全吗?
想把它写成 - >在哪里( “价格<或价格>?”,$ minimumPrice,$ maximumPrice) 是否有任何poissibility?
,我不能将其分割成2,其中陈述,因为计划写查询 - >其中( “1或2”) - >其中( “3 OR 4”)
如果我有复杂的WHERE
个条款我使用DB适配器的->quoteInto()
方法,如:
$where = '('
. $dbAdapter->quoteInto('price1 < ?', $price1)
. ' OR '
. $dbAdapter->quoteInto('price1 > ?', $price1)
. ')'
. ' AND '
. '('
. $dbAdapter->quoteInto('price2 < ?', $price2)
. ' OR '
. $dbAdapter->quoteInto('price2 > ?', $price2)
. ')'
;
$select->where($where);
这是有效的变体,但它并不好:) – 2010-10-23 16:05:59
试试:
$query->where('(price < ?', $minPrice)
->orWhere('price > ?)', $maxPrice)
->where('some = ?', $some_other_variable);
将导致: where ((price < $minPrice) OR (price > $maxPrice)) AND (some = $some_other_variable)
注意双(())中或部分
这是不适合的 - 我需要写这样的建设这样的 - >哪里( - >其中(1)或 - >其中(2)) - >其中( - >其中(3)或 - >其中(4)) – 2010-10-10 11:12:01
有些时候,你会希望做哪些大约有多个括号SQL查询,其中,将用foreach进行剖析,但你不希望条件困扰于字符串操作。例如,你有ID和用户列表必须某些类型的,你可以试试这个:
$select = $this->select();
$subWhere = $this->select();
foreach(array_keys($idArr) as $key => $value) {
$subWhere->orWhere('id=?', $value);
}
$select->where(implode(' ', $subWhere->getPart('WHERE')))->where('type=?', 'customer');
这将导致“SELECT * FROM表WHERE((ID = X)OR (id = Y)OR(id = Z)...)AND(type ='customer');“
思想开发远一点,你可以扩展Zend_Db_Table_Abstract:
public function subWhere($col, $binds, $operands, $andOr = 'OR')
{
$subWhere = $this->select();
if(strtolower($andOr) == 'or') {
foreach($binds as $key => $value) {
$subWhere->orWhere($col.$operands[$key].'?', $value);
}
return implode(' ', $subWhere->getPart('WHERE'));
}
elseif (strtolower($andOr) == 'and') {
foreach ($binds as $key => $value) {
$subWhere->where($col.$operands[$key].'?', $value);
}
return implode(' ', $subWhere->getPart('WHERE'));
}
else {
return false;
}
}
而且使用它作为:
$this->select()->where($this->subWhere($col, $binds, $operands));
你当然应该允许混合$的cols,$操作数=阵列( )违约为'=?'等等,但为了简单起见,我把它留下了。但是我相信我们应该使用IN(),BETWEEN ...和...之类的原生SQL函数,而不是...和...? Zend Framework并不会让你的生活变得非常简单。
$select->where($db->quoteInto('field1 < ? OR', $minPrice)
. $db->quoteInto('field1 > ?', $maxPrice))
->where($db->quoteInto('field2 < ? OR', $value2)
. $db->quoteInto('field2 > ?', $value3));
我问过同样的问题。见杰森的答案在这里:http://stackoverflow.com/questions/1179279/grouping-where-clauses-with-zend-db-table-abstract – Mark 2010-10-11 16:51:16