Doctrine不跟踪实体中某些字段的更改

时间:2016-08-18 16:57:24

标签: php symfony doctrine-orm

使用PHP 7,Symfony 3.1.3和Doctrine 2.5.4。

我正在尝试将更新保存到实体。该实体是另一个类的子类(类的简化版本):

class ProjectRequest
{
    // No Doctrine or Symfony annotations on the parent class
    protected $title;

    public function getTitle()
    {
        return $this->title;
    }

    public function setTitle($title)
    {
        $this->title = $title;

        return $this;
    }
}

class ProjectRequestNewProject extends ProjectRequest
{
    /**
     * @var string
     * @ORM\Column(name="title", type="string")
     * @Assert\NotBlank()
     */
    protected $title;

    /**
     * @var string
     * @ORM\Column(name="new_project_description", type="string")
     * @Assert\NotBlank()
     */
    protected $description;

    /**
     * @return string|null
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * @param string $description
     * @return ProjectRequestNew
     */
    public function setDescription(string $description): ProjectRequestNew
    {
        $this->description = $description;

        return $this;
    }
}

当我保存新记录时,它可以正常工作(简化):

$entity = new ProjectRequestNewProject();

//... Symfony form management

$form->handleRequest();

$entityManager->persist($entity);
$entityManager->flush();

当我尝试更新实体时,事情变得奇怪。我的保存逻辑非常正常。我在多个其他项目(甚至是同一项目中的其他实体)上使用了相同的逻辑。

$projectRequest = $this->getDoctrine->getRepository('ProjectRequestNewProject')->find($id)

 $form = $this->createForm(
    ProjectRequestNewProjectType::class,
    $projectRequest,
    [
        'entityManager' => $entityManager,
        'action' => $this->generateUrl('project_request_new_project_edit', ['id' => $id])
    ]
);

$form->handleRequest($request);

if ($form->isSubmitted() && $form->isValid()) {
    // save request
    $entityManager->flush();

    // redirect to show project request
    return $this->redirect(
        $this->generateUrl(
            'project_request_show',
            ['id' => $id]
        )
    );
}

使用此逻辑,如果我更新实体上的$title字段,则Doctrine会按预期更新记录。但是,如果我只更改$description字段,则Doctrine不会更新数据库。

查看Symfony配置文件,我可以看到数据被发送到服务器并正常转换。在确定实体是否已更改时,Doctrine似乎忽略了对子实体上声明的字段的更改。

我无法找到有关搜索Google或StackOverflow的这种行为(我可能没有使用正确的搜索字词),我无法弄清楚为什么Doctrine忽略对子实体字段的更改以确定是否需要更新数据库。

同样,如果我将更改标题和描述,那么对这两个字段的更改将保存到数据库中,但如果我只更改描述,则更改将不会保存到数据库中

我在文档中是否遗漏了某些内容,或者扩展基类的实体是否存在问题?

1 个答案:

答案 0 :(得分:0)

我最后使用Doctrine's Single-Table Inheritance Mapping来修复此问题。