代码之家  ›  专栏  ›  技术社区  ›  se_pavel

Zend Framework Complex Where语句

  •  2
  • se_pavel  · 技术社区  · 16 年前

    此方法作为官方示例发布

    这种方法安全吗?

    ->where(“价格”<?还是价格,$minimumPrice,$maxiumprice) 有可能吗?

    ->其中(“3或4”)

    4 回复  |  直到 15 年前
        1
  •  1
  •   Jason Austin    16 年前

    如果我有复杂的 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);
    
        2
  •  2
  •   Robert MacLean    14 年前

    $query->where('(price < ?', $minPrice)
    ->orWhere('price > ?)', $maxPrice)
    ->where('some = ?', $some_other_variable);
    

    将导致: where ((price < $minPrice) OR (price > $maxPrice)) AND (some = $some_other_variable)

    注意两个(()在或部分

        3
  •  1
  •   Ahti Ahde    15 年前

    有些时候,您可能希望使用foreach来生成在多个where条件周围带有括号的SQL查询,但是您不想为字符串操作而烦恼。例如,您将拥有一个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');
    

    这将导致“从表中选择*,其中((id=X)或(id=Y)或(id=Z)…)和(type='customer');”

    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,$operands=array()默认为“=?”等等,但为了简单起见,我把它忘了。但我相信我们应该使用本机SQL函数,比如IN(),介于。。。而且…,不是介于。。。还有。。。?Zend框架并不能让你的生活变得很轻松。

        4
  •  1
  •   Crusader    14 年前
    $select->where($db->quoteInto('field1 < ? OR', $minPrice)
                 . $db->quoteInto('field1 > ?', $maxPrice))
           ->where($db->quoteInto('field2 < ? OR', $value2)
                 . $db->quoteInto('field2 > ?', $value3));
    
    推荐文章