我有一个自引用实体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);
}
}接下来,我创建了两个产品(I 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)了,但没有结果。
发布于 2016-07-07 12:14:16
我做了更多的研究,自己找到了解决方案:
我的函数removeConnection()有一个错误:我从connectedBy和connectedWith这两个列表中删除了产品,这是错误的。相反,我应该像在addConnection()中那样做
$this->connectedWith->removeElement($product);
$product->connectedBy->removeElement($this);https://stackoverflow.com/questions/38237596
复制相似问题