使用Yii Active Record查找最多一列

f0ofjuux  于 2022-11-09  发布在  其他
关注(0)|答案(6)|浏览(115)

我如何通过Yii Active Record找到数据库中一列的最大值?
我可以用纯sql和createCommand方法来做,但是我想用活动记录和CDbCriteria来做class.is有什么办法吗?

tyg4sfes

tyg4sfes1#

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

$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_viewfindpostp_80659

cyvaqqii

cyvaqqii2#

这样可以避免创建不必要的临时对象:

$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();
zsbz8rwp

zsbz8rwp3#

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

$criteria = new CDbCriteria;
$criteria->order = 'column DESC';
$row = Model::model()->find($criteria);
$somevariable = $row->column;
zaq34kh6

zaq34kh64#

如果需要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;
}
unguejic

unguejic5#

$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();
y3bcpkx1

y3bcpkx16#

这就是了。

function getMaxId( $modelName ){
    $criteria = new CDbCriteria;
    $criteria->order = 'id DESC';
    $model = $modelName::model()->find( $criteria );
    return $model->id;
}

相关问题