首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >删除自引用@ManyToMany连接

问删除自引用@ManyToMany连接
EN

Stack Overflow用户
提问于 2016-07-07 04:34:59
回答 1查看 151关注 0票数 2

我有一个自引用实体Product

代码语言:javascript
复制
<?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)和两个产品之间的连接:

代码语言:javascript
复制
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)

现在,我要删除与以下代码的连接:

代码语言:javascript
复制
$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)了,但没有结果。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-07-07 12:14:16

我做了更多的研究,自己找到了解决方案:

我的函数removeConnection()有一个错误:我从connectedBy和connectedWith这两个列表中删除了产品,这是错误的。相反,我应该像在addConnection()中那样做

代码语言:javascript
复制
$this->connectedWith->removeElement($product);
$product->connectedBy->removeElement($this);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38237596

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档