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

后端 未结 4 1857
天涯浪人
天涯浪人 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 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
            
    }
    

提交回复
热议问题