Skip to content

Semantical Error on conditionally added joins to the QueryBuilder #624

Open
@yguedidi

Description

@yguedidi

I got this error

QueryBuilder: [Semantical Error] line X, col X near 't.other IN(':
Error: 't' is not defined.

With the following code:

        if (empty($things) && empty($others)) {
            return [];
        }

        $qb = $this->createQueryBuilder('s');

        $condition = $qb->expr()->orX();

        if (!empty($things)) {
            $condition->add('s.thing IN(:things)');
            $qb->setParameter('things', $things);
        }

        if (!empty($others)) {
            $condition->add('t.other IN(:others)');
            $qb
                ->addSelect('t')
                ->join('s.thing', 't')
                ->setParameter('others', $others)
            ;
        }

        $qb->andWhere($condition);

        return $qb->getQuery()->getResult();

Activity

ServerExe

ServerExe commented on Jan 27, 2025

@ServerExe

Same here. When using private methods to join tables but using the joined aliases in the select([]) method, PHPStan complains.

Example:

$qb = $this
    ->createQueryBuilder('foo')
    ->select(['foo', 'bar', 'baz']);

$this
    ->joinBar($qb)
    ->joinBaz($qb);

It complains:

 ------ ------------------------------------------------------------------------------------------------------------------- 
  Line   src/Repository/FooRepository.php                                                                                  
 ------ ------------------------------------------------------------------------------------------------------------------- 
  64     QueryBuilder: [Semantical Error] line 0, col 13 near 'bar, baz,': Error: 'bar' is not defined.  
         🪪  doctrine.dql                                                                                                                                                                                                 
 ------ -------------------------------------------------------------------------------------------------------------------

These are my methods:

private function joinBar(QueryBuilder $qb): self
{
    $qb->join(\sprintf('%s.bar', 'foo'), 'bar');

    return $this;
}

private function joinBaz(QueryBuilder $qb): self
{
    $qb->join(\sprintf('%s.baz', 'foo'), 'baz');

    return $this;
}

Side note: Reason why I am using sprintf() is because actually I am using constants but for presentation reasons here I used pure strings.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      Semantical Error on conditionally added joins to the QueryBuilder · Issue #624 · phpstan/phpstan-doctrine