gpt4 book ai didi

php - doctrine2 查询同花后的顺序

转载 作者:行者123 更新时间:2023-11-30 00:52:04 24 4
gpt4 key购买 nike

我在使用 Symfony2 和 Doctrine2 的项目中遇到问题,因为我无法在刷新后操纵查询的顺序...

我有 2 个具有 OneToOne 双向关系的实体:用户和团队这是一个例子来说明我所面临的情况:

RedTeam have a team manager (user) : Mark

GreenTeam have a team manager (user): Jack

如果我把 Redteam 的团队经理换成 Jack 那么我应该这样做

RedTeam have a team manager : Jack

GreenTeam have a team manager : 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;
}

}

这是我 Controller 的一部分

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

通常贪婪队需要先更新以避免重复条目异常,但Nooodoctrine2总是直接从RedTeam开始..

这里是异常(exception):

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

为什么在团队更新之前没有触发器?触发器不是很好的做法,但它会简化您的问题。

关于php - doctrine2 查询同花后的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20882490/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com