Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Yii Active Record to find max of one column

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?

like image 362
Moein Hosseini Avatar asked Aug 29 '12 20:08

Moein Hosseini


3 Answers

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

like image 101
Stephen305 Avatar answered Oct 12 '22 23:10

Stephen305


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();
like image 37
Martin Komara Avatar answered Oct 12 '22 22:10

Martin Komara


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;
like image 1
Josh Avatar answered Oct 13 '22 00:10

Josh