Count in Many_Many relation


I could not find a Solution for the

Following Problem:

I have 2 Models: Folder and Data. These are linked with a Many-Many Relationship using the table FolderData. I am trying to Output the Name of the Folder together with the number of Data (count). Unfortunately I could Not find a Solution… Is this possible with One query at all? Or do I need n+1 queries? Thanks for your help :)

Statistical query

BTW, I prefer to use counters, they don’t require additional stat query at all.

I do Not See a Reason to use stat queries cause they perform for each Folder One extra query… However how can I do that without changing the dB Design? Thanks!

Actually, they don’t.

Yii will perform ONE extra query like

select folderId, count(*) from FolderData group by folderId 

and merge results then.

(but you have to use ‘with’ syntax to activate eager loading)

Kinda Yii’s rock’n’roll magic!

Ah cool thx. But with stat-relationship it is not possible to order by it.

How to achieve that? Showing all folders with count data, ordered by count?

You can reorder resulting array by standard php functions.

But in your place I’d reconsider using counters. Srsly.