Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine 2 : Select specific columns from Entity and its Join entities

I have this scenario where I have to select specific columns of Entity and join entities.

This statement works and fetches all columns of all Entities.
$this->createQueryBuilder('e')
        ->select('e','bs','t')
        ->leftJoin('e.bits', 'bs')
        ->leftJoin('bs.tests', 't')
        ->getQuery()
        ->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY)

Question 1

I want something like this

Try 1

$this->createQueryBuilder('e')
        ->select('e.title','bs.name','bs.content','t.id','t.date')
        ->leftJoin('e.bits', 'bs')
        ->leftJoin('bs.tests', 't')
        ->getQuery()
        ->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY)

But this throws errors like

[Semantical Error] line 0, col -1 near 'SELECT e.title,': Error: Cannot select entity through identification variables without choosing at least one root entity alias.

Try 2

$this->createQueryBuilder()
        ->select('e.title','bs.name','bs.content','t.id','t.date')
        ->from($this->_entityName, "e")
        ->leftJoin('e.bits', 'bs')
        ->leftJoin('bs.tests', 't')
        ->getQuery()
        ->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY)

This throws error Warning: Missing argument 1 for Doctrine\ORM\EntityRepository::createQueryBuilder(),

Try 3

This works but only if I select from just 1 Entity 
    $this->createQueryBuilder('e')
        ->select('e.title')
        ->leftJoin('e.bits', 'bs')
        ->leftJoin('bs.tests', 't')
        ->getQuery()
        ->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY)

Question 2 Is there a smart way to remove specific columns from select query instead of writing all columns. I have around 30 columns in an Entity and its really messy to write 27 of them which I want in a query

Thanks

like image 607
Kiran Ambati Avatar asked Jan 24 '26 13:01

Kiran Ambati


1 Answers

Try to use partial like this

$this->createQueryBuilder()
    ->select(['partial e.{title}','partial bs.{name, content}','partial t.{id, date}'])
    ->from($this->_entityName, "e")
    ->leftJoin('e.bits', 'bs')
    ->leftJoin('bs.tests', 't')
    ->getQuery()
    ->getArrayResult
like image 75
Maxim Strutinskiy Avatar answered Jan 27 '26 07:01

Maxim Strutinskiy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!