【问题标题】:Doctrine 2 : ManyToOne cascade remove causes the referenced entity to be deleted原则 2:ManyToOne 级联删除导致引用的实体被删除
【发布时间】:2017-01-26 20:35:42
【问题描述】:

我有一个设置,其中有产品提要,每个提要都有许多产品。非常简化的设置如下所示:

饲料模型:

/**
 * 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;
}

现在您可以看到我已启用级联,因为我希望在删除提要时自动删除所有产品。

但是...目前,当我删除产品时,也会导致原始提要也被删除。我怀疑这与关系的设置方式有关,但我似乎无法弄清楚哪里出了问题。

谁能更清楚地说明这种情况?

【问题讨论】:

  • 我认为您应该在映射到您的产品的“OneToMany”上的 Feed 类中定义此级联。实际上,您已经定义了单向关系。您必须定义双向关系
  • 感谢您的解释!对学说有点新意。我在想 CASCADE 在 MySQL 中是如何工作的,你只需要在孤儿上定义它,所以我认为它在 Doctrine 中有类似的方法。
  • Orm 对我来说也是一个难题!但是,一旦设置好它就像魔术一样。您可以在这篇文章中获得更精确的详细信息:stackoverflow.com/questions/25515007/….

标签: php doctrine-orm cascade cascading-deletes


【解决方案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 的 Product 对象也将被删除。

这是双向关系。

更多信息:

cascade={"remove"}

  • 当拥有方(Feed)被删除时,相反方的实体将被删除,但前提是实体(产品)不属于 Feed 之外的其他人。

orphanRemoval="true"

  • 与上述相同,但如果实体(产品)由另一个实体拥有,ORM 会忽略

【讨论】:

    猜你喜欢
    • 2020-06-25
    • 1970-01-01
    • 1970-01-01
    • 2014-07-17
    • 2013-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多