[英]DQL LEFT JOIN - sql example
运行良好的SQL是:
SELECT ro.id_role
,rr.id_role_resource
,re.id_resource
FROM resource re
LEFT JOIN role_resource rr
ON rr.resource_id = re.id_resource
LEFT JOIN role ro
ON ro.id_role = rr.role_id
现在我必须写DQL-这是表shema:
角色: id_role, name
角色id_role_resource, role_id, resource_id, permission
: id_role_resource, role_id, resource_id, permission
角色id_role_resource, role_id, resource_id, permission
资源: id_resource, controller,action ...
最后一个表中的表中没有相应的记录role_resource。 这就是为什么我需要在DQL中保留此左联接查询的原因。
通常,如果您有一个带有$roles
属性的Resource
实体和正确的注释( OneToMany
, ManyToMany
),则您的role_resource
表( 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');
但是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');
但是,如果您希望 role_resource
表具有其自身的auto_increment ID并可以在Doctrine查询中访问,则Doctrine需要了解该表-它需要映射到单独的实体,并且需要明确说明以下事实:正在加入资源,RoleResources和角色。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.