尝试添加新实体时,我也收到此错误。
A new entity was found through the relationship 'Application\Entity\User#chats'
that was not configured to cascade persist operations for entity: ###.
To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity or
configure cascade persist this association in the mapping for example @ManyToOne(..,cascade={"persist"}).
我的情况是我试图保存不应该保存的实体。实体关系已填充并试图保存(在 Many2Many 中User
有Chat
,但 Chat 是一个临时实体),但发生了一些冲突。
所以如果我使用cascade={"persist"}
我会得到不需要的行为 - 垃圾实体被保存。我的解决方案是从任何保存实体中删除非保存实体:
// User entity code
public function removeFromChats(Chat $c = null){
if ($c and $this->chats->contains($c)) {
$this->chats->removeElement($c);
}
}
保存代码
/* some code witch $chat entity */
$chat->addUser($user);
// saving
$user->removeFromChats($chat);
$this->getEntityManager()->persist($user);
$this->getEntityManager()->flush();