I'm trying to create a query for retrieving objects from a Doctrine database, sorted by the number of members of a specific one-to-many relationship.
More specifically: I have two Entities: Person and Federation. A person can be a member of one federation (Person has 'federation' relationship), and a federation may have n people (Federation as 'people' relationship).
I would like to create a DQL Query that would return the list of Federations, ordered by how many people are members of that Federation. Something along these lines:
SELECT f FROM AcmeStatsBundle:Federation f ORDER BY [number of members of f.people]
That would be the first step. There is an additional second step, which I don't know if is possible to achieve with a single query, which would be filtering the members of the relation prior the counting. Like so:
SELECT f FROM AcmeStatsBundle:Federation f ORDER BY [number of (f.people p where p.attr = value)]
That second one would be the optimal result, but the first one satisfies my needs, if the second case is not feasibly in a single query.
Thanks in advance.
SELECT f, COUNT(p) as qtd FROM AcmeStatsBundle:Federation f LEFT JOIN f.people p WHERE p.attr = :some_value GROUP BY f.id ORDER BY qtr
:D – Friesian