如何解决添加需要属性 @ManyToOne(..,cascade={"persist"}) 的新对话时的错误

问题描述 投票:0回答:1

我收到此错误:

A new entity was found through the relationship 'App\Entity\ReseauxSociaux\Conversation#utilisateur1' that was not configured to cascade persist operations for entity: John_Doe. 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"}).

这是在我的控制器中

    /**
 * @Route("/new-conversation-user", name="newConversationUser", methods={"POST"})
 */
public function newConversationUser(Request $request)
{
    $donnees = json_decode($request->getContent());
    $otherUser = $this->entityManager->getRepository(User::class)->find($donnees->id);
    
    if (is_null($otherUser)) {
        throw new \Exception("L'utilisateur n'a pas été trouvé");
    }

    $userConnected = $this->getUser();
    // cannot create a conversation with myself
    if ($otherUser->getId() === $userConnected->getId()) {
        throw new \Exception("C'est profond mais vous ne pouvez pas créer une conversation avec vous-même");
    }

    // Check if conversation already exists
    $conversation = $this->conversationRepository->findConversationByUser1User2(
        $otherUser->getId(),
        $userConnected->getId()
    );

    $conversation = new Conversation();
    $conversation->setUtilisateur1($userConnected);
    $conversation->setUtilisateur2($otherUser);

    $this->entityManager->persist($conversation);
    $this->entityManager->flush();
    
    
    return $this->json($conversation, 201, [], ['groups' => 'message:read']);
}

这是我的实体对话:

 class Conversation
    {
        ...
        /**
         * @ORM\ManyToOne(targetEntity=User::class, inversedBy="conversations")
         * 
         */
        private $utilisateur1;

        /**
        * @ORM\ManyToOne(targetEntity=User::class)
        */
        private $utilisateur2;
    }

然后我将

cascade={"persist"}
添加到我的属性 utilisateur1 中,如下所示:

/**
* @ORM\ManyToOne(targetEntity=User::class, inversedBy="conversations", cascade={"persist"})
* 
*/
private $utilisateur1;

然后我得到:

"An exception occurred while executing a query: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '[email protected]' for key 'UNIQ_8D93D649E7927C74'"

php symfony doctrine
1个回答
0
投票

我明白为什么,有这样一行:

$this->entityManager->getUnitOfWork()->clear(User::class);

我用它来测试,我从chatGpt 得到这个对不起大家......

© www.soinside.com 2019 - 2024. All rights reserved.