It’s pretty straight-forward to include a stat relation (e.g. post count of a blog user) as a column of a CGridView.
However, is it possible to make that column sortable?
By default it is not because the stat relation is not an attribute. If I add it explicitly to the sort object’s attributes array, I get a query error when I click to sort the column, because a column with that name does not exist in the query.
The root of the problem seems to be that stats are ALWAYS computed with a separate query regardless of the value of "together". So it looks like it will never be possible to sort by it.
Has anybody been able to create a gridview with a column for a stat that is sortable?
It seems to me like something that should be absolutely trivial so perhaps I’m missing something?
There is a trend to move much of the data logic to the application layer, wich sometimes makes the code hard to write. Despite softark’s solution being brilliant (I learned from his wiki post), what about creating an SQL view within the database, like:
create view user_view as
select user.*,
user_post.count as post_count
from user,
(select user_id, count(*)
from post
group by user_id) as user_post
where user.id = user_post.user_id;
?
Then you create an application model UserView for that SQL view and you can: display, search, sort, etc. without any hesitation.
I know this is a broader discussion than simply solving your specific problem here, but it is a valid option imho. Hope it helps