2016-07-07 9 views
1

を削除:Iは自己参照エンティティ<code>Product</code>有する自己参照@ManyToMany接続

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) 

<?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); 
    } 
} 

次へ私は2つの製品(IDが1及び2)及び両製品間の接続を作成

$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

他の方法で関係を削除しようとしていますか? $ product2-> removeConnection($ product1); –

+0

それは面白いですが、はい - それは動作します! @理解しました。なぜ想像できますか? –

+0

これは双方向の関係であるためです。 ManyToManyでは、そうする必要があります。しかし、私は自動的にすべての関係を削除する方法が存在するかどうかわかりません(注釈などのように...) –

答えて

1

私は自分自身をもう少し研究し、解決策を見つけた:

My機能removeConnection()はバグがあります:私は間違っている、両方のリストから製品を取り出しconnectedByconnectedWith。代わりに、私はそれを好むべきですaddConnection()

$this->connectedWith->removeElement($product); 
$product->connectedBy->removeElement($this);