Doctrine - A new entity was found through the relationship

后端 未结 7 2047
天涯浪人
天涯浪人 2020-11-30 05:41

since 2 weeks, we are having this problem while trying to flush new elements:

CRITICAL: Doctrine\\ORM\\ORMInvalidArgumentException:

A new

7条回答
  •  一生所求
    2020-11-30 05:52

    I got this error too when tried to add new entity.

    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"}).
    

    My case was that I tried to save entity, that shouldn't be saved. Entity relations was filled and tried to be saved (User has Chat in Many2Many, but Chat was a temporary entity), but there were some collisions.

    So If I use cascade={"persist"} I get unwanted behaviour - trash entity is saved. My solution was to remove non-saving entity out of any saving entities:

    // User entity code
    public function removeFromChats(Chat $c = null){
        if ($c and $this->chats->contains($c)) {
            $this->chats->removeElement($c);
        }
    }
    

    Saving code

    /* some code witch $chat entity */
    $chat->addUser($user);
    
    // saving
    $user->removeFromChats($chat);
    $this->getEntityManager()->persist($user);
    $this->getEntityManager()->flush();
    

提交回复
热议问题