I solved the problem myself, who cares, here's the code: https://github.com/sc0rp1d/schedule/blob/e510ad72b95e9491af9ff2f5692d9b0e469140f7/models/Group.php#L95
public function filled($bool = true) { $schedule_table = ScheduleElement::model()->tableName(); $semester = Semesters::model()->actual(); $criteria = $this->getDbCriteria(); $criteria->params[':semester_id'] = $semester->id; for ($i = 1; $i <= 2; $i++) { for ($j = 1; $j <= 6; $j++) { $sql = "(SELECT COUNT(*) FROM `$schedule_table` WHERE `$schedule_table`.`week_number` = $i AND `$schedule_table`.`week_day` = $j AND `$schedule_table`.`group_id` = `t`.`id` AND `$schedule_table`.`semester_id` = :semester_id) " . ($bool ? ">" : "=") . " 0"; $criteria->addCondition($sql, $bool ? 'AND' : 'OR'); } } return $this; }