如何通过Yii Active Record找到数据库中一列的最大值?
我可以通过纯sql和createCommand
方法来实现,但我想通过Active Record和CDbCriteria
class来实现它。有没有办法做到这一点?
答案 0 :(得分:12)
您需要更改选择条件,如下所示。
$model = new Model;
$criteria=new CDbCriteria;
$criteria->select='max(column) AS maxColumn';
$row = $model->model()->find($criteria);
$somevariable = $row['maxColumn'];
参考:
答案 1 :(得分:6)
这可以避免创建不必要的临时对象:
$criteria = new CDbCriteria;
$criteria->select = 'max(column)';
// additional where conditions, if you so wish
$criteria->addColumnCondition(array('published' => 1));
$model = SomeModel::model();
$value = $model->commandBuilder->createFindCommand(
$model->tableName(), $criteria)->queryScalar();
答案 2 :(得分:0)
如果您需要WHERE子句:
在控制器中:
$max = $model->getMax($filter);
模特:
public $maxColumn = 0;
public function getMax($filter = null)
{
/* Get max in column1 WHERE column2 = $filter */
$criteria = new CDbCriteria;
$criteria->select = 'MAX(t.column1) as maxColumn';
$criteria->condition = 't.column2 LIKE :parm';
$criteria->params = array(':parm'=>$filter);
$tempmodel = $this->find($criteria);
$max = $tempmodel['maxColumn'];
return $max;
}
答案 3 :(得分:0)
您可以通过DESC限制结果和顺序,例如
$criteria = new CDbCriteria;
$criteria->order = 'column DESC';
$row = Model::model()->find($criteria);
$somevariable = $row->column;
答案 4 :(得分:0)
$model = MyModel::model();
$maxId = $model->getCommandBuilder()
->createSqlCommand('SELECT MAX(id) FROM '.$model->tableName())
->queryScalar();
$maxId = Yii::app()->db
->createCommand('SELECT MAX(id) FROM '.$model->tableName())
->queryScalar();
答案 5 :(得分:-1)
就是这样。
for(int i = 0; i< myObject.FieldOfArrayBytes; i++)
ms.Write(littlechunk);
// continue while all data are wrote.