使用此查询:
$qb = $this->createQueryBuilder('r');
$qb->leftJoin('r.users', 'u')
->addSelect('count(u.id) as user_count')
->groupBy('r.id');
我得到结果集:
Array
(
[0] => Array
(
[0] => Array
(
[id] => 45
[role_name] => ROLE_ADMIN
[description] => Admin roles
)
[user_count] => 1
)
[1] => Array
(
[0] => Array
(
[id] => 47
[role_name] => ROLE_OPERATOR
[description] => Operator role
)
[user_count] => 1
)
[2] => Array
(
[0] => Array
(
[id] => 48
[role_name] => ROLE_TEST
[description] => ROLE_TEST
)
[user_count] => 0
)
)
是否存在将所有属性转换为同一级别的明智方法?现在,角色位于带有0键的子数组中。
所需结果:
Array
(
[0] => Array
(
[id] => 45
[role_name] => ROLE_ADMIN
[description] => Admin roles
[user_count] => 1
)
[1] => Array
(
[id] => 47
[role_name] => ROLE_OPERATOR
[description] => Operator role
[user_count] => 1
)
[2] => Array
(
[id] => 48
[role_name] => ROLE_TEST
[description] => ROLE_TEST
[user_count] => 0
)
)
答案 0 :(得分:1)
根据我的评论
我认为这是没有机会的,因为首先选择的是 对象本身,第二个是另外选择的stmt。如果 user_count将是您对象的属性,它将起作用。
相反,您可以在Role实体上添加一个名为private $countUsers
的新属性,并使用Doctrine LifecycleCallbacks事件PostLoad
设置其值
Symfony权利:https://symfony.com/doc/current/doctrine/lifecycle_callbacks.html
学说事件:https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/events.html#lifecycle-events