我的项目使用Symfony2和Doctrine2时出现问题,因为我无法在刷新后操纵查询的顺序......
我有2个具有OneToOne双向关系的实体:用户和团队 这是一个例子来说明我挣扎的情况:
RedTeam有一个团队经理(用户):Mark
GreenTeam有一个团队经理(用户):杰克
如果我将Redteam的团队经理更改为Jack,那么我应该
RedTeam有一个团队经理:杰克
GreenTeam有一个团队经理:null
这是我的实体类与我制作的setter
用户:
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'
答案 0 :(得分:0)
在一对一关系中,您必须先取消其他团队的团队经理。
即。要做:
UPDATE team SET manager=:user_id WHERE id=:team_id
首先需要执行此操作:
UPDATE team SET manager = null WHERE id=:user_id
为什么在团队更新之前没有触发器?触发不是很好的练习,但它会简化你的问题。