I would recommend you write the query in sql first and then translate it to yii criteria
// assuming you have 2 tables (items, folders) and you have one to many relation
// folder can have many items and an item belongs to a folder
$criteria = new CDbCriteria;
$criteria->with = ['folder'];
$criteria->select = "folder.name, COUNT(items.id) as total";
$criteria->group = "folder.name";
$criteria->having = "total > 1";
I tried your succestion, but I get the same result as before.
Please have a look at my code below (now I use variables in German, because there might be some failure with naming …
The condition is passed from the controller, but this does not matter …
public function relations() {
return array(
'Heft'=>array(self::BELONGS_TO, 'Hefte', 'Heft_Id'),
);
}
public function search($condition = NULL) {
$criteria=new CDbCriteria;
$criteria->with = array('Heft');
echo $condition; // for test purpose I see, that the condition is ok.
if ( $condition ) {
$criteria->select = "*, COUNT(Heft.Id) as countItems";
$criteria->group = "Heft.Id";
$criteria->having = $condition;
I get the proper result, when the condition is: countItems = 1
When the condition is countItems > 1 then I only get one record of each "Heft".