Check if alias exists?
Asked Answered
R

2

11

How I could check if the alias is already defined?

There is no method for check this.

Thats not working because I got only the ROOT alias and no join aliases.

/** @var $query \Doctrine\ORM\QueryBuilder */
$query->getRootAliases()

The parts is another invalid option for me...

$query->getDQLPart()

Returns only the parts like "select, from, etc.".

And thats the error I would "ignore".

[Semantical Error] line 0, col 254 near '_user LEFT': Error: '_user' is already defined.

How could I check if the alias exists?

Ramsgate answered 20/3, 2014 at 15:31 Comment(1)
The query builder keeps track of join aliases but doesn't expose them: github.com/doctrine/doctrine2/blob/…Gullible
S
23

You could use PHP native in_array function to check if the value exists in the array or not.

in_array($alias, $qb->getAllAliases())
Spirelet answered 18/4, 2016 at 14:18 Comment(2)
getAllAliases is available from Doctrine 2.5, for anyone else who comes across thisHelio
$queryBuilder->getRootAliases()Macron
Q
9

You get this error because you're trying to join with an already defined alias.

A solution would be to check join DQL parts. In your repository method you could do something like this:

$joinDqlParts = $queryBuilder->getDQLParts()['join'];
$aliasAlreadyExists = false;

/* @var $join Query\Expr\Join */
foreach ($joinDqlParts as $joins) {
    foreach ($joins as $join) {
        if ($join->getAlias() === '_user') {
            $aliasAlreadyExists = true;
            break 2;
        }
    }
}

if ($aliasAlreadyExists === false) {
    $queryBuilder->innerJoin('parenttable._user', '_user')

}

So you only join if you didn't joined already.

Quinidine answered 19/11, 2014 at 15:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.