5

Yii Active Record如何找到数据库中一列的最大值?

我可以通过纯 sql 和createCommand方法来完成,但我想通过 Active Record 和CDbCriteria类来完成。有什么办法吗?

4

6 回答 6

12

您需要按如下方式更改选择标准。

$model = new Model;
$criteria=new CDbCriteria;
$criteria->select='max(column) AS maxColumn';
$row = $model->model()->find($criteria);
$somevariable = $row['maxColumn'];

参考:

http://www.yiiframework.com/forum/index.php/topic/6730-how-can-i-use-max-in-find-method/page_view_findpost_p_80659 _ _ _ _

于 2012-08-29T20:56:02.793 回答
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();
于 2013-08-08T04:12:16.493 回答
1

您可以通过 DESC 限制结果和顺序,例如

$criteria = new CDbCriteria;
$criteria->order = 'column DESC';
$row = Model::model()->find($criteria);
$somevariable = $row->column;
于 2014-04-04T06:20:50.420 回答
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;
}
于 2013-07-19T21:47:37.907 回答
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();
于 2020-06-17T22:43:34.680 回答
-1

就是这个。

function getMaxId( $modelName ){
    $criteria = new CDbCriteria;
    $criteria->order = 'id DESC';
    $model = $modelName::model()->find( $criteria );
    return $model->id;
}
于 2018-02-20T08:42:22.713 回答