如何在Yii中执行选择并计算一个查询

时间:2018-08-31 07:17:59

标签: php sql yii

我想在Yii中执行此SQL查询:

select count(id), userID from tableName where type = 'admin' and dateAdded between '2018-07-01' and '2018-08-01' group by userID

是否可以通过findAll()countAll()或其他Yii方法运行此查询?我不想使用findAllBySQL()

2 个答案:

答案 0 :(得分:0)

您可以使用以下解决方案在一个语句中执行选择并计数:

$model=Model::find()->where([your conditions])->count();

答案 1 :(得分:0)

Yii 1.1

$data = MyModel::model()->findAll([
    'select' => [
        'count(id) as count', 
        'userID'
    ],
    'condition' => "type = 'admin' and dateAdded between '2018-07-01' and '2018-08-01'",
    'group' => 'userID',
]);

您还需要向count添加MyModel属性:

class MyModel extends CActiveRecord {

    public $count;

    // ...
}

然后您可以将计数映射到ID:

$counts = CHtml::listData($data, 'userId', 'count');

或在foreach中访问它:

foreach ($data as $model) {
    echo "$model->userID - $model->count\n";
}

Yii 2

$data = Post::find()
    ->select([
        'count(id) as count',
        'userID',
    ])
    ->where("type = 'admin' and dateAdded between '2018-07-01' and '2018-08-01'")
    ->groupBy('userID')
    ->asArray()
    ->all();

映射:

$counts = ArrayHelper::map($data, 'userID', 'count');

Foreach:

foreach ($data as $row) {
    echo "{$row['userID']} - {$row['count']}\n";
}