【问题标题】:Doctrine find() returning controller教义 find() 返回控制器
【发布时间】:2012-07-18 17:08:32
【问题描述】:

我的控制器中有一个方法,它从 JMSSerializerBundle 获取一个反序列化的对象并返回完整的对象,准备好被持久化。我这样做的原因是返回更新的对象,因此,当它被持久化时,它不会将所有内容重置为默认值。

运行时,此方法最终会在指示的行上抛出 ErrorException 并将其放入我的日志中:Warning: ReflectionProperty::setValue() expects parameter 1 to be object, null given in C:\DevelopmentProjects\keobi-web\vendor\doctrine\lib\Doctrine\ORM\Mapping\ClassMetadata.php line 177 (uncaught exception) at C:\DevelopmentProjects\keobi-web\vendor\symfony\src\Symfony\Component\HttpKernel\Debug\ErrorHandler.php line 65

由于某种原因,EntityManager 方法find 正在返回(根据get_classDefaultController,此方法的控制器类。 setFieldValue 说它是 NULL。

让我感到困惑的是,如果找不到实体,则应该抛出 Doctrine\ORM\EntityNotFoundException。它没有被抛出。所以,它显然是在找到实体,而不是正确地返回它......

传入参数$data是JSMSerializerBundle反序列化的对象。 $em 绝对是 EntityManager$metadata 绝对是 ClassMetadata

我在这里不知所措。不知道如何继续。

受保护的函数 processEntity($data)
{
$em = $this->getDoctrine()->getEntityManager(); $metadata = $em->getClassMetadata(get_class($data)); $fqcn = $元数据->getName(); $blankEntity = 新 $fqcn(); $id = 数组();

$this->get('logger')->debug('Incoming object type: ' . get_class($data)); # Keobi\ModelBundle\Entity\User
$this->get('logger')->debug('Blank entity type: ' . get_class($blankEntity)); # Keobi\ModelBundle\Entity\User
$this->get('logger')->debug('FQCN: ' . $fqcn); # Keobi\ModelBundle\Entity\User

foreach ($metadata->getIdentifierFieldNames() as $identifier)
{
  $id[$identifier] = $metadata->getFieldValue($data, $identifier);

  if (!$id[$identifier])
  {
    $this->get('logger')->debug(sprintf("Identifer '%s' missing. Assuming the object is new.", $identifier));
    return $data;
  }
}

$entity = $em->find($metadata->getName(), $id);

$this->get('logger')->debug(get_class($entity)); # Keobi\RestAPIBundle\DefaultController

foreach ($metadata->getFieldNames() as $field)
{
  $value = $metadata->getFieldValue($data, $field);
  $default = $metadata->getFieldValue($blankEntity, $field);

  if ($value <> $default)
  {
    $metadata->setFieldValue($entity, $field, $value); # <- throws ErrorException
    $this->get('logger')->debug(sprintf("Updated field '%s' in %s", $field, get_class($entity)));
  }
}

return $entity;  

}

【问题讨论】:

    标签: symfony doctrine-orm


    【解决方案1】:

    看起来 Doctrine2 有问题。我将其更新为Github repo 的最新 HEAD 提交。令我困惑的是,这种方法实际上在不久前就奏效了。

    找不到解决问题的确切提交,但在撰写本文时,提交是 93cef612701b9e8caaf43c745978cd4fbd9d4e4e

    【讨论】:

      【解决方案2】:
      $entity = $em->find($metadata->getName(), $id);
      

      您需要指定要搜索的存储库,例如:

      $entity = $em->getRepository('EntitiesBundle:Entity')->find(...)
      

      【讨论】:

      • $em-&gt;find() 实际上是$em-&gt;getRepository($entity)-&gt;find() (doctrine-project.org/api/orm/2.2/…) 的快捷方式。我希望就这么简单。两种方法我都试过了。
      猜你喜欢
      • 2014-02-07
      • 2017-10-08
      • 1970-01-01
      • 2021-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多