问题描述:

If I have a company entity, with a one to many association to user entities, how can I get a list of company entities, sorted by the number of users?

网友答案:

Here is my solution but it is maybe not the best way:

SELECT 
    c, COUNT(u.id) as num_users
FROM
    Acme\Model\Company c
    LEFT JOIN c.users u
GROUP BY
    c.id
ORDER BY
    num_users DESC

After hydrating the results, you will get an array like:

array(
    array(
        0 => /* entity instance */,
        'num_users' => 123
    ),
    array(
        0 => /* entity instance */,
        'num_users' => 111
    ),
    // ...
 )

So you have to filter the results:

 return array_map(
     function ($result) { return $result[0]; },
     $results
 );

And that's it!

Maybe you can avoid the filtering part tweaking the hydration part.

相关阅读:
Top