2016-09-19 91 views
1

我有一個設置,我有產品供稿,每個供稿有許多產品。非常簡單的設置是這樣的:學說2:ManyToOne級聯刪除導致刪除參考實體

飼料模型:

/** 
* Class Feed represents a single feed as supplier by a supplier 
* @package App\Model 
* @Entity @Table(name="feeds") 
*/ 
class Feed 
{ 
    /** 
    * @var int 
    * @Id @Column(type="integer") @GeneratedValue 
    */ 
    protected $id; 
} 

產品型號:

/** 
* Class Product is the base for either supplied and current products 
* @package App\Model 
*/ 
class Product 
{ 
    /** 
    * @var int 
    * @Id @Column(type="integer") @GeneratedValue 
    */ 
    protected $id; 

    /** 
    * @var Feed 
    * @ManyToOne(targetEntity="App\Model\Feed", cascade={"remove"}) 
    * @JoinColumn(name="id_feed", referencedColumnName="id", onDelete="CASCADE") 
    */ 
    protected $feed; 
} 

現在你可以看到我已經級聯啓用,因爲我希望所有的產品在Feed被刪除時自動刪除。

但是......此刻,當我刪除產品時,它也會導致原始Feed te被刪除。我懷疑它與這個關係是如何建立關係的,但我似乎無法弄清楚它出錯的地方。

任何人都可以在這種情況下看到更多的光線嗎?

+0

我想你應該定義該級聯飼料類擁有的ORM忽略將「OneToMany」映射到您的產品。實際上,你已經定義了單向關係。你必須定義雙向關係 – Delphine

+0

感謝您的解釋!一種新的教義。我正在考慮CASCADE如何在MySQL中工作,你只需要在孤兒中定義它,所以我認爲它在Doctrine中有類似的方法。 –

+0

Orm對我來說也是一個難題!但是,一旦設定好就像魔術一樣。你可以在這篇文章中獲得更多精確的細節:http://stackoverflow.com/questions/25515007/doctrine-cascade-remove-vs-orphanremoval-true?rq=1。 – Delphine

回答

1

飼料型號:

/** 
    * Class Feed represents a single feed as supplier by a supplier 
    * @package App\Model 
    * @Entity @Table(name="feeds") 
    */ 
    class Feed 
    { 
     /** 
     * @var int 
     * @Id @Column(type="integer") @GeneratedValue 
     */ 
     protected $id; 

     /** 
     * @var Feed 
     * @OneToMany(targetEntity="App\Model\Product", mappedBy="feed", orphanRemoval=true, cascade={"remove"}) 
     * 
     */ 
     protected $products;  

    } 

產品型號:

/** 
* Class Product is the base for either supplied and current products 
* @package App\Model 
*/ 
class Product 
{ 
    /** 
    * @var int 
    * @Id @Column(type="integer") @GeneratedValue 
    */ 
    protected $id; 

    /** 
    * @var Feed 
    * @ManyToOne(targetEntity="App\Model\Feed", inversedBy="products") 
    * @JoinColumn(name="id_feed", referencedColumnName="id") 
    */ 
    protected $feed; 
} 

現在,如果你刪除一個Feed對象,鏈接到該飼料產品的對象也將被刪除。

這是雙向關係。

更多信息:

級聯=在逆側{「刪除」}

  • 實體將被刪除,而持有端(飼料)被刪除,但只有當該實體(產品)不屬於Feed以外的所有者。

orphanRemoval =「真」

  • 同上,但如果實體(產品)是由另一實體