Yii框架中的SQL查询帮助(计数,分组依据)!

时间:2015-10-29 12:27:18

标签: php mysql yii

我想知道是否有人可以帮助我用CDbCriteria编写此查询。

SELECT COUNT(*), vrste_odsustva_id FROM doob.calendar WHERE radnik_id=19 group by vrste_odsustva_id;

我试过这个,但他没有给我列出任何东西

$criteria= new CDbCriteria;
    $criteria->select = '*, COUNT(*)';  // is also the default value so you can leave this line out
    $criteria->condition = 'vrste_odsustva_id != NULL';
    $criteria->params = array(':radnik_id' => $radnik_id);
    $criteria->group = 'vrste_odsustva_id';
    $odsustva=Calendar::model()->find($criteria);

我只是得到一个空数组。

注意:它是Yii 1.1.6版本

3 个答案:

答案 0 :(得分:3)

您可以使用Yii querybuilder

$dbCommand = Yii::app()->db->createCommand("
               SELECT COUNT(*) as tot, vrste_odsustva_id FROM `calendar` WHERE radnik_id=19 GROUP BY `vrste_odsustva_id`
            ");
$data = $dbCommand->queryAll();//output

如果您想使用CDbCriteria,那么:

$criteria = new CDbCriteria();
$criteria->select = 'count(*) AS model_attr, vrste_odsustva_id';//your model must have these attributes 
$criteria->group = 'vrste_odsustva_id';
$criteria->condition = 'radnik_id= 19';
$count = Calendar::model()->findAll($criteria);
foreach ($count AS $data) {
    echo "type: ".$data["vrste_odsustva_id"]." count: ".$data["model_attr"]."<br/>";
}

答案 1 :(得分:0)

   Users::find()->where(['role_id'=>'3'])->count();

您可以使用上面的syntex

答案 2 :(得分:0)

您也可以使用:

$criteria = new CDbCriteria();
$criteria->select = 'COUNT(*) AS total';
$criteria->condition = 'vrste_odsustva_id != NULL AND radnik_id=:radnik_id';
$criteria->params = array(':radnik_id'=>$radnik_id);
$criteria->group = 'vrste_odsustva_id';
$odsustva = Calendar::model()->findAll($criteria);