How can I find max value of one column in database by Yii Active Record?
I can do it by pure sql and createCommand
method,but I wanna do it by Active Record and CDbCriteria
class.is there any way to do it?
You will want to change the select criteria as follows.
$model = new Model;
$criteria=new CDbCriteria;
$criteria->select='max(column) AS maxColumn';
$row = $model->model()->find($criteria);
$somevariable = $row['maxColumn'];
Reference:
http://www.yiiframework.com/forum/index.php/topic/6730-how-can-i-use-max-in-find-method/page_view_findpost_p_80659
This avoids creating an unnecessary temporary object:
$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();
You can just limit the result and order by DESC e.g
$criteria = new CDbCriteria;
$criteria->order = 'column DESC';
$row = Model::model()->find($criteria);
$somevariable = $row->column;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With