Search code examples
phpjoinormdoctrine-ormdql

Doctrine DQL JOIN


I have the following entities mapped with Doctrine 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).

If I had to do this in plain SQL, I would write:

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?


Solution

  • Ok, I finally found a way to do it with JOINs only (significantly faster on MySQL):

    SELECT r
    FROM Restaurant r,
         Zone z
    JOIN z.descendants d
    WHERE r.zone = d
    AND z = ?1;