我有三个表:
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"
]
]
但是当我加入实体用户加入user_roles加入角色时,结果如下:
$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"
]
]
我错在哪里?我怎样才能正确制作?谢谢!
首先,我建议使用 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 应该自行处理多对多关系及其链接表,还是我错过了什么?