[英]Doctrine DQL JOIN
I have the following entities mapped with Doctrine 2 : 我将以下实体映射到“学说2” :
class Zone
{
/**
* @ManyToOne(targetEntity="Zone", inversedBy="children")
* @var Zone
*/
protected $parent;
/**
* @OneToMany(targetEntity="Zone", mappedBy="parent")
* @var Zone[]
*/
protected $children;
/**
* @ManyToMany(targetEntity="Zone")
* @var Zone[]
*/
protected $descendants;
}
class Restaurant
{
/**
* @ManyToOne(targetEntity="Zone")
* @var Zone
*/
protected $zone;
}
Basically, a Zone has a parent, and therefore children. 基本上,区域具有父母,因此也有孩子。 Because children may have children themselves, each Zone keeps a list of all its descendants as well. 因为孩子可能自己也有孩子,所以每个区域也会保留其所有后代的列表。
Each Restaurant is assigned a Zone. 每个餐厅都分配有一个区域。
What I want to do, is to perform a DQL JOIN to return all Restaurants in a specific Zone (including all of its descendants). 我要执行的操作是执行DQL JOIN,以返回特定区域中的所有餐厅(包括其所有后代)。
If I had to do this in plain SQL, I would write: 如果必须在普通的SQL中执行此操作,我会写:
SELECT r.* from Zone z
JOIN ZoneDescendant d ON d.zoneId = z.id
JOIN Restaurant r ON r.zoneId = d.descendantId
WHERE z.id = ?;
Is it possible to do this with Doctrine DQL, without adding a $restaurants
property on the Zone, and having to complexify the domain model uselessly? 是否可以使用Doctrine DQL做到这一点,而无需在区域上添加$restaurants
属性,而不必无用地复杂化域模型?
Ok, I finally found a way to do it with JOINs only (significantly faster on MySQL): 好的,我终于找到了一种仅使用JOIN的方法(在MySQL上明显更快):
SELECT r
FROM Restaurant r,
Zone z
JOIN z.descendants d
WHERE r.zone = d
AND z = ?1;
我可以想到的在单个DQL查询中执行此操作的唯一方法是使用子查询:
SELECT r FROM Restaurant r WHERE r.zone IN (SELECT zc.id FROM r.zone z JOIN z.children zc WHERE z.id = :zoneId) OR r.zone = :zoneId
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.