繁体   English   中英

DQL左联接-SQL示例

[英]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, permissionid_role_resource, role_id, resource_id, permission角色id_role_resource, role_id, resource_id, permission

资源: id_resource, controller,action ...

最后一个表中的表中没有相应的记录role_resource。 这就是为什么我需要在DQL中保留此左联接查询的原因。

通常,如果您有一个带有$roles属性的Resource实体和正确的注释( OneToManyManyToMany ),则您的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM