Searching and Sorting by Count of Related Items in CGridView

The topic title refers to the Wiki article Searching and Sorting by Count of Related Items in CGridView.

I am interested in it because a few months ago I wrote a CActiveRecord extension to help with exactly this and it also works by using sub-queries. My extension also tries to handle filtering.

The code in SQActiveRecord is very ugly. And my comments are even worse. But I’ve found it useful.

It would be nice if it could be used also outside of the CGV context (see the readme) but I haven’t figured it out yet.

This is a perennially vexing issue for Yii users so I’m interested in what folk think about these workarounds.

Hi fsb, thank you for your interest in the wiki article that I have written. :)

I agree that extending CActiveRecord with sub queries is very useful.

I think that the STAT relation SHOULD have the abilities that your SQActiveRecord provides.

In my opinion, what a STAT relation is is just a sub query. Isn’t it?

And what we want to do in constructing CDbCriteria is …


[*]use it in "select"

[*]use it in "where"

[*]use it in "order by"


Why can not a STAT relation provide the corresponding sub query for them? The sub query could be easily constructed from the definition of the STAT relation. I’m wondering why the STAT relation doesn’t have such functionality by now.

Ah, you know, it’s not a complaint, but a sheer question. :)

That’s a good point. In SQActiveRecord the subqueries are specified by a function returning an array. It would be possible to avoid that and use STAT relations specs to generate the scopes that SQActiveRecord uses. If I had the time it would be fun to try.