我收到此错误:
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'"
我明白为什么,有这样一行:
$this->entityManager->getUnitOfWork()->clear(User::class);
我用它来测试,我从chatGpt 得到这个对不起大家......