简体   繁体   中英

SQL query help in Yii framework(count, group by)!

I was wondering if anyone can help me with writing this query with CDbCriteria.

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

I tryed with this but he didn't list me anything

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

I just get an empty array.

Note: It's Yii 1.1.6 version

You could use Yii querybuilder for this:

$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

If you want to use CDbCriteria then:

$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/>";
}
   Users::find()->where(['role_id'=>'3'])->count();

您可以在上面使用syntex

You can also use this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM