我在编写symfony2应用程序时遇到了问题。
情况: 我想创建一个实体“A”的副本,然后修改其属性“foo”。但是,A和Foo通过OneToOne关系相关联,这会触发错误:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '9' for key
UNIQ_41A6A445D7FA9592
我的实体如下:
/**
* AcmeBundle\Entity\A
*
* @ORM\Table()
* @ORM\Entity(repositoryClass="AcmeBundle\Entity\ARepository")
*/
class A
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\OneToOne(targetEntity="Mvcc\AcmeBundle\Entity\Foo")
*
*/
protected foo;
getFoo(){
return $this->foo;
}
setFoo($foo){
$this->foo = $foo;
return $this;
}
}
问题: 在我的控制器中,我执行以下操作:
/*start*/
/*1) I create a clone aBis of a, instance of A.its foo attribute is connected to foo1.*/
$aBis = clone($a);
/*2) I modify the attribute foo for a */
$foo2 = new Foo();
$a->setFoo($foo2);
$em->persist($foo2)
$em->persist($aBis);
$em->persist($a);
$em->flush();
/*end*/
我想,当涉及到刷新时,事实上在某种程度上“a”和“aBis”都具有属性foo1并不让教条继续下去并且看到$ a将其属性更改为新的foo。 你知道如何解决这个问题吗?
我的实际问题有点复杂(它涉及更深层次的关系和工作单元)。但是,我想我总结了这里的主要问题。
非常感谢提前!
此致
答案 0 :(得分:0)
如果要克隆具有关系的实体,请在所涉及的所有实体中实施public function __clone()
实体中的示例:
public function __clone()
{
if ($this->id) {
// if the $foo property is a ManyToMany, ManyToOne or OneToMany
$foo = $this->getFoo();
$this->foo = new ArrayCollection();
foreach ($foo as $row) {
$this->foo[] = $row;
}
// if the $foo property is a OneToOne
$foo = $this->getFoo();
$this->foo = clone $foo;
}
}
在控制器:
中$myOriginal = new A();
$myClone = clone $myOriginal;
// then persist
$em->persist($myClone);
// and flush
$em->flush();
实体的OneToMany 实施:
/**
* AcmeBundle\Entity\A
*
* @ORM\Table()
* @ORM\Entity(repositoryClass="AcmeBundle\Entity\ARepository")
*/
class A
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\OneToMany(targetEntity="Mvcc\AcmeBundle\Entity\Foo")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="foo_id", referencedColumnName="id")
* })
*/
protected foo;
getFoo(){
return $this->foo;
}
setFoo($foo){
$this->foo = $foo;
return $this;
}