Doctrine 2(Symfony)使用自定义字段的结果集映射始终为null

时间:2016-10-07 12:56:58

标签: symfony doctrine-orm

我在Symfony 2存储库中执行以下本机查询:

$sql = "SELECT f.id, f.title, 'hi' AS custom_field FROM my_feed f";

$em = $this->getEntityManager();
$rsm = new \Doctrine\ORM\Query\ResultSetMapping($em);
$rsm->addEntityResult('MedicalCoreBundle:Feed', 'f');
$rsm->addFieldResult('f', 'id', 'id');
$rsm->addFieldResult('f', 'title', 'title');
$rsm->addFieldResult('f', 'custom_field', 'custom_field');

$query = $em->createNativeQuery($sql, $rsm);
$result = $query->getResult();

我在custom_field实体中创建了非映射属性getCustomField及其getter和setter setCustomField以及Feed

映射的字段是水合适当的,但当我添加custom_field RSM时,我收到以下错误:Notice: Undefined index: custom_field [...] in symfony\..\AbstractHydrator.php

实体代码

// non mapped field
private $custom_field;

public function getCustomField()
{
    return $this->custom_field;
}

public function setCustomField($number)
{
    $this->custom_field = (int) $number;

    return $this;
}

我在这里做错了什么?

2 个答案:

答案 0 :(得分:0)

感谢您的错误,您似乎在custom_ F 某个地方有 F 而不是 f

答案 1 :(得分:0)

您应该映射custom_field或使用addScalarResult代替addFieldResult

...
$rsm->addScalarResult('custom_field', 'custom_field');
...

结果看起来像

[
    [0=>entity, 'custom_field'=>custom_field value],
    [0=>entity, 'custom_field'=>custom_field value],
    ...
]