Doctrine 2: how do you use a subquery column (in the SELECT clause)

后端 未结 4 1821
天涯浪人
天涯浪人 2020-12-30 00:28

I\'m trying to do a simple select query with a subquery in the SELECT clause and have simply not found a way to do it. I\'ve tried with both DQL and with the QueryBuilder, n

相关标签:
4条回答
  • 2020-12-30 00:58
    $query = $qb->select('a')
        ->addSelect('(SELECT at.addresstypeName
                FROM e:Addresstype at
                WHERE at.addresstypeId = a.addresstypeId) AS addresstypeName'
            )
        ->from('e:Address', 'a')
        ->where('a.addressId = :addressId')
        ->setParameter('addressId', 1);
    
    0 讨论(0)
  • 2020-12-30 00:59

    I know this is an old question, but if you want, you could have used another query builder as your subquery:

     $qb->select("a")
                ->addSelect("(" . $qb2->select("at.addresstypeName")
                    ->from("e:Addresstype", "at")
                    ->where("at.addresstypeId = a.addresstypeId")
                    ->getDQL() . ") AS addresstypeName"
                )
                ->from('e:Address', 'a')
                ->where('a.addressId = :addressId')
                ->setParameter('addressId', 1);
    
    0 讨论(0)
  • 2020-12-30 01:02

    In my scenario what I needed was to look into a join and find an Id and use it as boolean, found 1 otherwise 0, then applying this to orderBy. DQL expressions worked only when combined with Where clause, which wasn't my case. So, a DQL subselect saved me.

    Adapted more or less to your scenario, it would look like this:

    // With QueryBuilder
    // In AddressRepository
    // Where one address may belong to several addressTypes
    
    public function getWithType($addressType){
    
    $qb = $this->createQueryBuilder('a1');
    $qb->addSelect('a1.someField', 'a1.otherField')
    $qb->addSelect(
            '(SELECT at.addressTypeName 
            FROM App\Entity\Address a2
            JOIN a2.addressType at
            WHERE at.id = '.$addressType.' AND a2.id = a1.id
            ) AS addressTypeName')
    //The rest part of the query
            
    }
    
    0 讨论(0)
  • 2020-12-30 01:07

    For me subquery with doctrine works with this query :

    $qb->select('e.field')
       ->addSelect('(SELECT count(mv.nm)
                    FROM Clt\Bundle\MyBundle\Entity\MV mv
                    LEFT JOIN Clt\Bundle\MyBundle\Entity\M ma WITH  mv.nm=ma.nm
                    WHERE mv.ne=e.ne and ma.nm is null
                    ) AS nm'
       )
       ->from($this->_entityName, 'e')
       ->leftJoin('e.m', 'm')
       ->where($qb->expr()->eq('t.id'.$typeModule, $idElementModule));
    

    Note that in the left join you must use WITH instead of ON...

    0 讨论(0)
提交回复
热议问题