gavec
gavec

Reputation: 205

Convert queryBuilder result into associative array

im looking for way, how to convert query builder result into associative array. But what I need is including relation data from another table. If I use getArrayResult() method, it gives me an array, but without foreign keys. And I need foreign keys included with nested array with data of associative db table. EDIT: Here is my code:

$qb = $this->_em->createQueryBuilder();
$qb->select('p');
$qb->from('XXX\MyBundle\Entity\Entity1', 'p');

$qb->leftJoin('p.FK1','u');
$qb->andWhere('u.Attr1 = :attr1');
$qb->setParameter('attr1', $appId);
$qb->andWhere('u.Attr2 IS NULL');
$qb->leftJoin('u.FK2', 'v');
$qb->andWhere('v.Attr3 = :attr3');
$qb->andWhere('v.Attr4 IS NULL');
$qb->setParameter('attr3', $userId);


$result = $qb->getQuery()->getArrayResult();

I need this conversion becouse of SOAP. It could not return complex object as nested objects of entities.

Upvotes: 1

Views: 3210

Answers (1)

Gmajoulet
Gmajoulet

Reputation: 700

First, you need to write this function in your Entity1Repository.php

Since you're using the createQueryBuilder() method, you don't need to use select and from methods. In your example, you're writing the joins, but you're not asking the query to return those joins.

Try this code :

<?php

namespace XXX\\MyBundle\Entity;

use Doctrine\ORM\EntityRepository;

class Entity1Repository extends EntityRepository
{
    public function getEntityWithJoins()
    {
        return $this
            ->createQueryBuilder('p')
            ->addSelect('u')
            ->addSelect('v')
            ->leftJoin('p.FK1','u')
            ->andWhere('u.Attr1 = :attr1')
            ->setParameter('attr1', $appId)
            ->andWhere('u.Attr2 IS NULL')
            ->leftJoin('u.FK2', 'v')
            ->andWhere('v.Attr3 = :attr3')
            ->andWhere('v.Attr4 IS NULL')
            ->setParameter('attr3', $userId);
            ->getQuery()
            ->getArrayResult();
    }
}

Upvotes: 2

Related Questions