简体   繁体   English

如何删除子表行,但将其父表保留在准则orm 2的“类表继承”中?

[英]How can I delete a child table row but keep its parent in Class Table Inheritance in doctrine orm 2?

I have two entities, Item and SpecialItem 我有两个实体,Item和SpecialItem

SpecialItem extends Item, where Item is normal shopping item with price property, and the SpecialItem is a shopping item on sale with extra discount property. SpecialItem扩展了Item,其中Item是具有价格属性的普通购物商品,而SpecialItem是具有额外折扣属性的正在销售的购物商品。

I'm using Class Table Inheritance 我正在使用类表继承

The Item: 项目:

<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;


/**
 * Item
 *
 * @ORM\Table(name="item")
 * @ORM\Entity
 * @ORM\InheritanceType("JOINED")
 * @ORM\DiscriminatorColumn(name="item_type", type="string")
 * @ORM\DiscriminatorMap({"item" = "Item", "special" = "SpecialItem"})
 */

class Item
{
/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="IDENTITY")
 */
private $id;

/**
 * @var string
 *
 * @ORM\Column(name="title", type="string", length=255, nullable=false)
 */
private $title;

/**
 * @var string
 *
 * @ORM\Column(name="price", type="decimal", precision=10, scale=0, nullable=false)
 */
private $price;

/**
 * @var string
 *
 * @ORM\Column(name="description", type="text", length=65535, nullable=true)
 */
private $description;


}

The Special Item : 特殊项目:

<?php


 namespace AppBundle\Entity;

 use Doctrine\ORM\Mapping as ORM;

 /**
 * @ORM\Entity
 */
 class SpecialItem extends Item
 {

 /**
 * @var string
 *
 * @ORM\Column(name="discount", type="decimal", precision=10, scale=0,   nullable=false)
 */
 private $discount;


 }

If I created a SpecialItem and persisted it (now it has one row in table item and one row in table specialitem with discount value), and now I decided to remove the discount so the special item will now be a normal item. 如果我创建了一个SpecialItem并将其保留(现在表项目中有一行,表特殊项目中有一行具有折扣值),现在我决定删除折扣,因此特殊项目现在将成为普通项目。

How can I remove the discount related rows only not the whole item and change the DiscriminatorColumn to reflect the parent type Item ? 如何删除仅与折扣相关的行而不是整个项目,并更改DiscriminatorColumn以反映父类型Item?

As far as I know you can't change entity type(discriminator) directly. 据我所知,您不能直接更改实体类型(区分符)。

1) You could write plain SQL query (bad idea but id remain the same): 1)您可以编写普通的SQL查询(不好的主意,但id保持不变):

 DELETE FROM special_item WHERE id = 15;

2) More clean solution: create a new instance of the Item and copy the data from SpecialItem. 2)更干净的解决方案:创建Item的新实例并从SpecialItem复制数据。

class Item
{
     public static function fromSpecialItem(SpecialItem $specialItem)
     {
          $item = new self();
          $item->title = $specialItem->getTitle();

          return $item;
     }
}

$newItem = Item::fromSpecialItem($speciaItem);
$entityManager->remove($speciaItem);
$entityManager->persist($newItem);
$entityManager->flush();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM