我在使用Symfony2和Doctrine2的项目中遇到问题,因为在刷新后我无法操纵查询的顺序...
我有两个具有OneToOne双向关系的实体:用户和团队
这个例子说明了我遇到的情况:
RedTeam有一个团队经理(用户):Mark
GreenTeam有一个团队经理(用户):Jack
如果我将Redteam的团队经理更改为Jack,那么我应该
RedTeam有一个团队经理:Jack
GreenTeam有团队经理:null
这是我制作的二传手的实体课
用户名:
class User {
/**
* @ORM\OneToOne(targetEntity="Vci\MainBundle\Entity\Team" , mappedBy="teamManager")
*/
protected $managedTeam;
public function setManagedTeam(Team $managedTeam = null) {
if ($managedTeam != null && $this->managedTeam !=null ) {
$this->managedTeam->setTeamManager(null);
}
$this->managedTeam = $managedTeam ;
return $this;
}
}
球队
class Team {
/**
* @ORM\OneToOne(targetEntity="Vci\MainBundle\Entity\User" , inversedBy="managedTeam")
* @ORM\JoinColumn(nullable=true)
*/
protected $teamManager;
public function setTeamManager(User $teamManager = null) {
if ($teamManager != null && $this->teamManager!=null) {
$this->teamManager->setTeamManaged(null);
}
$this->teamManager = $teamManager;
if ($this->teamManager != null) {
$this->teamManager->setTeamManaged($this);
}
return $this;
}
}
这是我控制器的一部分
if ($request->getMethod() == 'POST') {
$form->bind($request); // the setter is called here
if ($form->isValid()) {
$teamManager = $this->get('vci_main.teammanager');
$teamgreen = $teamManager->findById(2);
$teamred = $teamManager->findById(1);
//the 2 teams are perfectly changed
//save in database
$this->em->flush(); // here is a flush and where the exception occure
通常,需要首先更新greedteam以避免重复输入异常,但是Nooo doctrine2总是直接从RedTeam开始。
这是例外:
An exception occurred while executing 'UPDATE Team SET teamManager_id = ? WHERE id = ?' with params [13, 1]:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '13' for key 'UNIQ_64D209219EF091'
最佳答案
在一对一关系中,您必须首先取消其他团队的团队经理。
即去做 :
UPDATE team SET manager=:user_id WHERE id=:team_id
您首先需要执行以下操作:
UPDATE team SET manager = null WHERE id=:user_id
为什么在团队更新之前没有触发器?触发不是很好的做法,但是它将简化您的问题。