如何在Yii中执行一个查询中的select和count
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在Yii中执行一个查询中的select和count相关的知识,希望对你有一定的参考价值。
我想在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()
。
答案
您可以使用以下解决方案在一个语句中执行select和count:
$model=Model::find()->where([your conditions])->count();
另一答案
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";
}
以上是关于如何在Yii中执行一个查询中的select和count的主要内容,如果未能解决你的问题,请参考以下文章