galabl
galabl

Reputation: 63

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

Upvotes: 2

Views: 1040

Answers (3)

Criesto
Criesto

Reputation: 2001

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/>";
}

Upvotes: 3

Kostas Mitsarakis
Kostas Mitsarakis

Reputation: 4747

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

Upvotes: 0

Ishan Shah
Ishan Shah

Reputation: 1676

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

You can use above syntex for that

Upvotes: 0

Related Questions