yiisoft/yii — pull request #801 by tudorilisoi (2012-06-07 23:45:14+00:00)
Title: Issue 82

This fixes issue #82 by implementing a $count_select attribute in relations and CdbCriteria
By specifying a $count_select in either of those, you trigger a subselect count like
(1)
```sql
SELECT COUNT(*) FROM (SELECT f1,f2...) sq
```

when performing CActiveRecord count with() related records.
In this situation(eager loading with $count_select!=='*'), the system does NOT strip the HAVING clause, which leads to incorrect record counting.

(1) 'f1,f2..' is a list compiled similariliy to CdbCriteria/CBaseActiveRelation select fields and aliases, which means it's joined hierarchically with the related records "count_select"s

I ran the test suite with Sqlite and MySQL, it does not seem to break existing functionality.

This count_select approach allows for better resource usage, since you can specify only a couple of fields for counting records, such as the 'main' AR primary key and the aggregate function used in the HAVING clause, such as
```php
count_select='id, COUNT(comment.id) AS comment_count';
```
The example above would generate a count() query like:

```sql
SELECT COUNT(*) FROM (SELECT `t`.`id` AS `t0_c0`, COUNT(comment.id) AS comment_count) sq
```

This fix is not by far perfect, it may not be the best approach and it lacks proper PHPDoc.
But those interested may pull and enjoy their CGridViews with HAVING clauses in the CActiveDataProvider