我有一个自引用实体Product
:
<?php
/** @Entity @Table(name="products") **/
class Product
{
/** @Id @Column(type="integer") @GeneratedValue **/
protected $id;
/** @Column(type="string", nullable=true) **/
protected $name;
/**
* @ManyToMany(targetEntity="Product", mappedBy="connectedBy", cascade={"all"})
*/
protected $connectedWith;
/**
* @ManyToMany(targetEntity="Product", inversedBy="connectedWith", cascade={"all"})
* @JoinTable(name="connection",
* joinColumns={@JoinColumn(name="product_id", referencedColumnName="id")},
* inverseJoinColumns={@JoinColumn(name="connected_product_id", referencedColumnName="id")}
* )
*/
protected $connectedBy;
public function __construct()
{
$this->connectedWith = new \Doctrine\Common\Collections\ArrayCollection();
$this->connectedBy = new \Doctrine\Common\Collections\ArrayCollection();
}
public function getConnected()
{
return $this->connectedWith;
}
public function addConnection(Product $product)
{
$this->connectedWith->add($product);
$product->connectedBy->add($this);
}
public function removeConnection(Product $product)
{
$this->connectedBy->removeElement($product);
$this->connectedWith->removeElement($product);
}
}
接下来,我创建了两个产品(ID 1和2)以及两个产品之间的连接:
mysql> select * from products;
+----+------+
| id | name |
+----+------+
| 1 | NULL |
| 2 | NULL |
+----+------+
2 rows in set (0.00 sec)
mysql> select * from connection;
+------------+----------------------+
| product_id | connected_product_id |
+------------+----------------------+
| 2 | 1 |
+------------+----------------------+
1 row in set (0.01 sec)
现在我想删除与此代码的连接:
$product1 = $entityManager->find('Product', 1);
$product2 = $entityManager->find('Product', 2);
$product1->removeConnection($product2);
$entityManager->persist($product1);
$entityManager->flush();
$product3 = $entityManager->find('Product', 1);
print count($product3->getConnected()) . "\n";
正如所料,代码打印0
作为结果。但是当我查看数据库时,连接条目仍然存在。可能是什么原因可以解决这个问题?
我已经尝试$entityManager->persist($product2)
,但无济于事。
答案 0 :(得分:1)
我研究了一点,自己找到了解决方案:
我的功能removeConnection()
有一个错误:我从两个列表connectedBy
和connectedWith
中删除了该产品,这是错误的。相反,我应该像在addConnection()
:
$this->connectedWith->removeElement($product);
$product->connectedBy->removeElement($this);