3

I have an entity NewsVersion with ManyToMany :

class NewsVersion
{
    ...

    /**
     * @var NewsCategory[]|ArrayCollection
     *
     * @ORM\ManyToMany(
     *     targetEntity="AppBundle\Entity\NewsCategory",
     *     cascade={"persist"}
     * )
     * @ORM\JoinTable(name="news_version_categories")
     */
    private $categories;

    ...

In my repository, when I call this :

    $qb = $this->createQueryBuilder('nv')
        ->select('nv')
        ->innerJoin('nv.categories', 'nvc')
        ->addSelect('nvc');

    return $qb->getQuery()->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);

I have :

enter image description here

But When I call this :

    $qb = $this->createQueryBuilder('nv')
        ->select('nv')
        ->innerJoin('nv.categories', 'nvc')
        ->addSelect('nvc.id');

I have :

enter image description here

Why nvc.id don't return id in categories array ? I want return only id from my category, but in categories array in NewsVersion entity (same as first screen)

Gaylord.P
  • 1,539
  • 2
  • 24
  • 54

2 Answers2

0

You should remove the ->addSelect('nvc.id')

and add the id of category in the select statement

$qb = $this->createQueryBuilder('nv')
        ->select('nv', 'nvc.id')
        ->innerJoin('nv.categories', 'nvc');
Mohamed Ben HEnda
  • 2,686
  • 1
  • 30
  • 44
  • This same ^^ My question is : Why nvc.id don't return id in categories array ? I want return only id from my category, but in categories array in NewsVersion entity (same as first screen). Thanks :) – Gaylord.P Nov 12 '17 at 16:18
  • 1
    You cann't merge the id category in the categories array – Mohamed Ben HEnda Nov 12 '17 at 16:43
0

You're making two separate queries for data; $queryBuilder->addSelect() creates a new one alongside the first.

It might make sense in plain SQL.

/* ->select('nv') */
SELECT *
FROM `nv`
/* all of nv's fields are returned in this set */

/* ->addSelect('nvc.id') */
SELECT `id`
FROM `nvc`
/* only nvc.id is returned in this set */

Doctrine wraps all of the queries' resultsets in an array, for your convenience, but doesn't combine them because they did not come from the same query.

Relevant source:

// class QueryBuilder
public function addSelect($select = null)
{
    // ...
    return $this->add('select', new Expr\Select($selects), true);
}
rhinosforhire
  • 1,305
  • 11
  • 20