我有一个带有两个实体CONTEXT和USER的symfony应用程序,它们每多对多关联关联两次:
class User
/**
* @ORM\ManyToMany(targetEntity="Context", inversedBy="members")
*/
private $contexts;
/**
* @ORM\ManyToMany(targetEntity="Context", inversedBy="managers")
* @ORM\JoinTable(name="manager_context")
*/
private $managerOfContexts;
class Context
/**
* @ORM\ManyToMany(targetEntity="User", mappedBy="contexts")
*/
private $members;
/**
* @ORM\ManyToMany(targetEntity="User", mappedBy="managerOfContexts")
*/
private $managers;
当我添加新用户并向用户添加上下文时,我总是会收到以下错误:
An exception occurred while executing 'INSERT INTO user_context
(user_id, context_id) VALUES (?, ?)' with params [5, 1]:
2 SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry
'2-1' for key 'PRIMARY'
似乎是SQL命令
DEBUG - INSERT INTO user_context (user_id, context_id) VALUES (?, ?)
DEBUG - INSERT INTO user_context (user_id, context_id) VALUES (?, ?)
执行两次。 我无法弄清楚原因。
我已经清除了symfony缓存,创建了新的数据库,并清除了浏览器缓存。
感谢您的帮助!
以下是我持久保存用户实体的代码:
/**
* @Route("/admin/user/new", name="admin_user_new")
*/
public function newAction(Request $request)
{
// 1) build the form
$user = new User();
$form = $this->createForm(UserType::class, $user, array('is_mode' => 'save','contexts' => null));
// 2) handle the submit (will only happen on POST)
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// 3) Encode the password (you could also do this via Doctrine listener)
$password = $this->get('security.password_encoder')
->encodePassword($user, $user->getPlainPassword());
$user->setPassword($password);
$user->addContext($this->getDoctrine()
->getRepository('AppBundle:Context')
->find(1));
$user->setActiveContext($this->getDoctrine()
->getRepository('AppBundle:Context')
->find(1));
// 4) save the User!
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$folder = new Folder();
$folder->setPrivate($user);
$em->persist($folder);
$em->flush();
// ... do any other work - like send them an email, etc
// maybe set a "flash" success message for the user
return $this->redirectToRoute('tasklist');
}
return $this->render('/admin/user/new.html.twig',
array('form' => $form->createView())
);
}