嗨,我有一个将人员添加到组的操作。
为了增加可用性,它的表格删除了已经在组中的人。
我的控制器操作如下所示:
public function addAction(UserGroup $userGroup)
{
$tempGroup = new UserGroup();
foreach ($userGroup->getUsers() as $user) {
$tempGroup->addUser($user);
}
$form = $this->container->get('form.factory')->create(new UserGroupQuickType(), $tempGroup);
$request = $this->container->get('request');
if ('POST' === $request->getMethod()) {
$form->submit($request);
if ($form->isValid()) {
$group = $form->getData();
/** @var $myUserManager UserManager */
$myUserManager = $this->container->get('strego_user.user_manager');
/** @var $em EntityManager */
$em = $this->container->get('em');
foreach ($group->getUsers() as $toInvite) {
$userGroup->addUser($toInvite);
}
$em->persist($userGroup);
$em->flush($userGroup);
}
}
return array(
'form' => $form->createView(),
'userGroup' => $userGroup
);
}
此代码引发异常:
A new entity was found through the relationship 'Strego\UserBundle\Entity\UserGroup#users'
that was not configured to cascade persist operations for entity: Degi.
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"}).
新发现的与之前的关系已经存在。这意味着用户“Degi”已经在组中并且不是新实体。
如果我省略持久性,我可以避免这个错误,但我会得到一个异常:Entity has to be managed or scheduled for removal for single computation
.
这是由于我的“用户组”实体的实体状态一直为 3(= 分离)
我对与我的用户组具有 1 对 1 关系的实体使用了相同的逻辑(使用临时组等),从那里我可以轻松地将人员添加到组中。但不是这个动作,它在逻辑上做完全相同的事情。
更新: 我之前的更新方向错误。但相比之下,工作的(几乎)相同的控制器:
public function addAction(BetRound $betRound)
{
$userGroup = new UserGroup();
foreach ($betRound->getUsers() as $user) {
$userGroup->addUser($user);
}
$form = $this->createForm(new UserGroupQuickType(), $userGroup);
$request = $this->getRequest();
if ('POST' === $request->getMethod()) {
$form->submit($request);
if ($form->isValid()) {
/** @var $betRoundManager BetRoundManager */
$betRoundManager = $this->container->get('strego_tipp.betround_manager');
/** @var $myUserManager UserManager */
$myUserManager = $this->container->get('strego_user.user_manager');
$group = $form->getData();
foreach ($group->getUsers() as $toInvite) {
if (!$betRound->getUserGroup()->hasUser($toInvite)) {
$betRound->getUserGroup()->addUser($toInvite);
}
}
$this->getDoctrine()->getManager()->flush();
return $this->redirect($this->generateUrl('betround_show', array('id' => $betRound->getId())));
}
}
return array(
'form' => $form->createView(),
'betRound' => $betRound
);
}