帮助在Zend中构建一个简单的SQL查询

时间:2011-05-20 10:55:06

标签: php sql zend-framework

我的SQL查询基于提供的数据。

例如:

// table
$table = new Model_MyTable_DbTable();

// data     
$columns = array( 'column1', 'column2', 'column3' );

// query        
$select = $table->select();
$select->where('deleted = ?',  '0' );

for( $i = 0; $i < count( $columns ); $i++ ) {
    if( $i == 0 ) {
          $select->where( $columns[$i] . ' > ?',  '0' );
    } else {
          $select->orWhere( $columns[$i] . ' > ?',  '0' );
    }
}

$select->where('disabled = ?',  '0' );

// print query
echo $select->assemble();die();

以上代码的结果如下:

SELECT `mytable`.* FROM `mytable` WHERE 
(deleted = '0') AND 
(column1 > '0') OR (column2 > '0') OR (column3 > '0') AND 
(disabled = '0')

但我想要这样的事情:

SELECT `mytable`.* FROM `mytable` WHERE 
(deleted = '0') AND 
(column1 > '0' OR column2 > '0' OR column3 > '0') AND 
(disabled = '0')

怎么可能?

谢谢

1 个答案:

答案 0 :(得分:5)

我认为这应该可以胜任:

    // table
    $table = new Model_MyTable_DbTable();

    // data     
    $columns = array('column1', 'column2', 'column3');

    // query        
    $select = $table->select();
    $select->where('deleted = ?', '0');

    $myOrParts = array();

    for ($i = 0; $i < count($columns); $i++) {                                                   
            $myOrParts []= $table->getAdapter()->quoteInto($columns[$i] . ' > ?', '0');           
    }

    $myWhere = implode(' OR ', $myOrParts);
    $select->where(new Zend_Db_Expr($myWhere));
    $select->where('disabled = ?', '0');

    // print query
    echo $select->assemble();
    die();