我有三张桌子:
users(id, firstName, lastName)
user_role(userId, roleId)
roles(id, role, userId)
我还有基于这些表的各个实体,在Symfony中生成:
users (id, firstName, lastName, user_role[])
user_role (users, roles)
roles (id, role)
当我进行以下查询时,它可以正常工作:
public function getAllUsers() {
$query = $this->getEntityManager()
->createQuery('
SELECT users_.firstName FROM MyApp:users users_
');
$result = $query->getArrayResult();
dump($result);
}
Result:
array:2 [▼
0 => array:1 [▼
"firstName" => "Paul"
]
1 => array:1 [▼
"firstName" => "John"
]
]
但是当我加入Entities用户JOIN user_roles JOIN角色时, 结果如下:
$query = $this->getEntityManager()
->createQuery('
SELECT users_.firstName, r.role FROM MyApp:users users_
JOIN users_.user_role ur
JOIN ur.roles r
');
$result = $query->getArrayResult();
dump($result);
Result:
array:2 [▼
0 => array:2 [▼
"firstName" => "Paul"
"role" => "admin"
]
1 => array:2 [▼
"firstName" => "Paul"
"role" => "user"
]
]
应该是:
array:2 [▼
0 => array:2 [▼
"firstName" => "Paul"
"role" => "admin"
]
1 => array:2 [▼
"firstName" => "John"
"role" => "user"
]
]
我哪里错了? 我怎样才能正确使用它? 谢谢!
答案 0 :(得分:2)
首先,我建议使用QueryBuilder(类似于Kero提出的)来完成这样的简单任务,以最大限度地减少查询本身的语法错误;
$query = $entityManager->createQueryBuilder()
->select('u.name name', 'r.role role')
->from(User::class, 'u')
->join('u.user_role', 'ur')
->join('ur.role', 'r')
->getQuery();
$result = $query->getResult(Query::HYDRATE_ARRAY);
如果输出的数据不正确,我敢打赌数据库中的数据同样不正确,问题出在其他地方。
其次,你有一个' UserRole'实体(我想,否则你不需要在查询中加入它),Doctrine应该自己处理多对多关系及其链表,还是我错过了什么?