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

ε祈祈猫儿з 提交于 2019-12-11 03:48:41

问题


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?


回答1:


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.




回答2:


I'm not entirely sure I understand what you are asking. I assume you want to know how to update users.virtualfield with the (CUSTOM_EXPRESSION)? That syntax would be:

update users set virtualfield = (CUSTOM_EXPRESSION)

If you wanted to update all rows.

If I'm off the mark can you please clarify your question?



来源:https://stackoverflow.com/questions/9728669/how-to-set-an-entity-field-that-does-not-exist-on-the-table-but-does-exists-in-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!