phpdoctrine-ormdoctrine-dbal

Doctrine: Hydrate models from raw SQL


I have the following custom query. I know its a simple one, so it can also be used as a DQL, but I have more complex ones too. But I want to know the way, how to do it even with more complex queries.

select j.*
from `shop`.`jobs` j
-- 2 joins
where j.`active` = true 
order by j.`priority` desc, j.`created` asc 

Sure have a Job model.

What I want:

An array of instances from the class Job, using the a raw sql. Like this:

array (6) {
    [0] => Job#12 (8) {
      ...
    }
    [1] => Job#13 (8) {
      ...
    }
    [2] => Job#14 (8) {
      ...
    }
    [3] => Job#16 (8) {
      ...
    }
    [4] => Job#17 (8) {
      ...
    }
    [5] => Job#18 (8( {
      ...
    }
}

Solution

  • Found it! Through the EntityManager's createNativeQuery function. And for the RSM I need to use the ResultSetMappingBuilder class.

    $rsm = new \Doctrine\ORM\Query\ResultSetMappingBuilder($this->getEntityManager());
    $rsm->addRootEntityFromClassMetadata(\Path\To\Model::class, 'alias');
    
    $nativeQuery = $this->getEntityManager()->createNativeQuery('-- query--', $rsm);
    
    $nativeQuery->getResult();