我有一个自引用实体 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)
但无济于事。
最佳答案
我进行了更多研究并自己找到了解决方案:
我的函数 removeConnection()
有一个错误:我从两个列表 connectedBy
和 connectedWith
中删除了产品,这是错误的。相反,我应该像在 addConnection()
中那样做:
$this->connectedWith->removeElement($product);
$product->connectedBy->removeElement($this);
关于php - 删除自引用的@ManyToMany 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38237596/