使用 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 会忽略子实体字段的更改以确定它是否需要更新数据库。
同样,如果我同时更改标题和描述,那么对这两个字段的更改将保存到数据库中,但如果我只更改描述,则更改将不会保存到数据库中.
文档中是否遗漏了某些内容,或者扩展基类的实体是否存在问题?
最佳答案
我最终使用 Doctrine's Single-Table Inheritance Mapping 解决了这个问题.
关于php - Doctrine 不跟踪实体中某些字段的更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39023705/