Help building a simple SQL query in Zend
My SQL query is based on data provided.
For example :
// 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();
Above code result into following query:
SELECT `mytable`.* FROM `mytable` WHERE
(deleted = '0') AND
(column1 > '0') OR (column2 > '0') OR (column3 > '0') AND
(disabled = '0')
But I want something like this:
SELECT `mytable`.* FROM `mytable` WHERE
(deleted = '0') AND
(column1 > '0' OR column2 > '0' OR column3 > '0') AND
(disabled = '0')
How it is possible ?
Thanks
I think this should do the job:
// 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();
精彩评论