Using Yii Active Record to find max of one column
Solution 1
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:
Solution 2
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();
Solution 3
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;
Moein Hosseini
I'm Moein who is into GNU/Linux, programming, open source and reading. Currently, I'm at AmirKabir University of Technology (Tehran Polytechnic) for M.S of Information Technology. My search interests are Natural Language Processing, Big Data and Machine Learning. Also, my thesis is about Forecasting the news impact on different aspects of social media users political opinions. Right now I work at BisPhone as Software Engineer. I took up my B.A in Computer Engineering from K.N.Toosi University of Technology and also graduated from Nodets for middle and high school.
Updated on June 18, 2020Comments
-
Moein Hosseini almost 4 years
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 andCDbCriteria
class.is there any way to do it? -
jsnfwlr almost 6 yearsThis isn't flexible enough. If I had a table of users, with their age, weight, and height stored and wanted to select the top 10 tallest people and get the maximum weight for that subset, I couldn't extend your answer to get the results I wanted at all.