通常情况下,如果您有一个Resource
实体具有$roles
属性和正确的注释(OneToMany
, ManyToMany
)然后你的连接表(role_resource
)不会有或不需要它自己的 auto_increment id。
这是因为 Doctrine 处理关联信息并根据它们知道何时需要连接表。 Doctrine 还知道在基于相同关联信息连接两个实体时使用什么条件。
因此,如果 SQL 查询使用 2 个连接子句通过第三个表连接两个表,则 DQL 查询只需要知道关联名称,并且它将拥有所有可用的“连接表”和“连接条件”信息。
所以一个简单的查询如下所示:
SELECT
/* i assume $idRole is the name of the property
* mapped to the id_role column
*/
ro.idRole,
/* i assume $idResource is the name of the property
* mapped to the id_resource column
*/
re.idResource
FROM YourNamespace\Resource re
JOIN re.roles
使用等效的 queryBuilder 语法:
$this->getEntityManager()->createQueryBuilder()
->select(array('ro.idRole', 're.idResource'))
->from('YourNamespace\Resource', 're')
->join('re.roles');
But JOIN
默认为INNER JOIN
因此我们希望通过将查询重写为以下方式来解决此问题:
SELECT ro.idRole,
re.idResource
FROM YourNamespace\Resource re
LEFT JOIN re.roles
使用等效的 queryBuilder 语法:
$this->getEntityManager()->createQueryBuilder()
->select(array('ro.idRole', 're.idResource'))
->from('YourNamespace\Resource', 're')
->leftJoin('re.roles');
然而如果你want the role_resource
表拥有自己的 auto_increment id 并且可以在 Doctrine 查询中访问,那么 Doctrine 需要了解该表——它需要映射到一个单独的实体,并且您需要明确您正在加入 Resources、RoleResources 的事实和角色。