automatix
automatix

Reputation: 14532

How to select entities via another entity type using Doctrine's QueryQuilder?

I want to select entities, that are not provided to the QueryBuilder#select(...). In raw SQL it would look like this:

SELECT x.*
FROM aaa a
INNER JOIN bbb b ON a.document_id = b.id
INNER JOIN ccc c ON b.client_user_id = c.id
INNER JOIN xxx x ON c.client_id = x.id
WHERE a.id = 123

Now I tried to implement this logic with the QueryBuilder:

$query = $queryBuilder->select('x')
    ->from(Aaa::class, 'a')
    ->join('a.bbb', 'b')
    ->join('b.ccc', 'c')
    ->join('c.xxx', 'x')
    ->where('a.id = :aId')
    ->setParameter('aId', $aId)
    ->getQuery()
;

But it doesn't work:

[Semantical Error] line 0, col -1 near 'SELECT x FROM': Error: Cannot select entity through identification variables without choosing at least one root entity alias.

How to get this working with with Doctrine's QueryQuilder?

Upvotes: 0

Views: 1405

Answers (1)

automatix
automatix

Reputation: 14532

Unfortunately it's not possible with Doctrine (see the statement of Benjamin Eberlei to this issue on GitHub).

The solution / workaround is to define the whole associations chain in the direction from Xxx to Aaa and then find the Xxx entity following the "path" starting FROM Xxx:

$query = $queryBuilder->select('x')
    ->from(Xxx::class, 'x')
    ->join('x.ccc', 'c')
    ->join('c.bbb', 'b')
    ->join('b.aaa', 'a')
    ->where('a.id = :aId')
    ->setParameter('aId', $aId)
    ->getQuery()
;

Upvotes: 0

Related Questions