[英]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.