Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve only entity id using Symfony QueryBuilder?

I'm trying to personalize a symfony 2.4 repository query to retrieve only some fields. Everything is ok with flat fields but when retrieving Entity fields, I only get the id (by default) but not the whole entity data. My query:

    $select = $this->createQueryBuilder('ca')
    ->select('ca.id, ca.name')
    ->leftJoin('ca.users', 'user')
    ->addSelect('(user) as users'); 

    $select->setMaxResults($count);

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

The result is: [{id: 1, name: "Some name", users: 1}, ...]

How can I change this query for users to contain the whole user data, like id, name, address, etc.?

like image 726
Vandervals Avatar asked May 31 '18 10:05

Vandervals


3 Answers

This works for me:

$select = $this->createQueryBuilder('ca')
    ->select('partial ca.{id, name}, users')
    ->leftJoin('ca.users', 'users');

$select->setMaxResults($count);

return $select->getQuery()->getArrayResult();
like image 67
Djengobarm Avatar answered Oct 16 '22 17:10

Djengobarm


You should try this way. You can use Partial.

$select = $this->createQueryBuilder('ca')
->select('partial ca.{id, name}')
->leftJoin('ca.users', 'users')
->addSelect('users'); 

A detailed description of this issue is available here. Doctrine2: Cannot select entity through identification variables without choosing at least one root entity alias

like image 26
Ramazan APAYDIN Avatar answered Oct 16 '22 15:10

Ramazan APAYDIN


change this:

->select('ca.id, ca.name')

to this:

->select('ca')
like image 1
Alessandro Minoccheri Avatar answered Oct 16 '22 16:10

Alessandro Minoccheri