Search code examples
phpsqldoctrine-ormrawsql

How to set an entity field that does not exist on the table but does exists in the raw SQL as an alias?


Lets say that we have a query like this one:

SELECT *, (CUSTOM_EXPRESSION) as virtualfield FROM users

The user's entity itself has the "virtualfield" but the mapping annotations no, since the table doesn't have this field.

Assuming that it is executed as a raw SQL, how do we populate the entity with the field above?


Solution

  • I've found the answer. To do so, you need to use a scalar value. For instance:

    $rsm = new \Doctrine\ORM\Query\ResultSetMappingBuilder($this->getEntityManager());
    $rsm->addRootEntityFromClassMetadata('Category', 'c');
    $rsm->addScalarResult('depth', 'depth');
    // [ ... ]
    $results = $q->execute();
    // Output will be a two-dimensional array 
    // array(0 => array(0 => CategoryObject, 'depth' => 'scalar-value', // ... ), // ...)
    

    Then, you can loop through it and set the property on the object if you want.