2014-06-19 27 views
0

在我的項目中,我有一個工作正常的包,現在我需要創建第二個包。我的第二個包的一個實體與我的第一個包+相同的字段具有相同的名稱,除了它必須有兩個額外的字段,並且我需要兩個包在數據庫的同一個表上工作。我如何從一個實體擴展到添加字段並保留擴展字段?是否可以重寫symfony2中的實體

知道我嘗試了經典的繼承,但我從教義

[Doctrine\DBAL\Schema\SchemaException] 
    The table with name 'postgres.article' already exists. 

這裏沒有驚喜,因爲該表確實存在,我怎麼做才能教義來更新它,而不是嘗試一個美麗的錯誤創造它?

回答

1

這叫做Class Table Inheritance。你可以有一個父實體和擴展它的子實體。您的附加字段存儲在您的子表中,主鍵鏈接到父表。

以下是我的一些現有代碼的基本示例,您可以根據自己的目的對其進行修改。我排除了訪問器方法。

陷阱!使用CTI時,您必須製作屬性protected,將它們設置爲私人不會讓它們共享。

父類

/** 
* Item 
* 
* @ORM\Table(name="`item`") 
* @ORM\InheritanceType("JOINED") 
* @ORM\DiscriminatorColumn(name="type_hint", type="string") 
* @DiscriminatorMap({"physical_item" = "PhysicalItem"}) 
* @ORM\Entity(repositoryClass="\Acme\MainBundle\Entity\ItemRepository") 
*/ 
class Item 
{ 
    /** 
    * @var integer 
    * 
    * @ORM\Column(name="id", type="integer") 
    * @ORM\Id 
    * @ORM\GeneratedValue(strategy="AUTO") 
    */ 
    protected $id; 

    /** 
    * @var string 
    * 
    * @ORM\Column(name="name", type="string", length=255) 
    */ 
    protected $name; 
} 

子表

/** 
* PhysicalItem 
* 
* @ORM\Table(name="`physical_item`") 
* @ORM\Entity 
*/ 

class PhysicalItem extends Item 
{ 
    /** 
    * @var integer 
    * 
    * @ORM\Column(name="id", type="integer") 
    * @ORM\Id 
    */ 
    protected $id; 

    /** 
    * @var string 
    * 
    * @ORM\Column(name="weight", type="string", length=255, nullable=true) 
    */ 
    protected $weight; 
} 

在這個例子中,你將有一個項目表和physical_item表。 item的所有屬性都存儲在那裏,而physical_item的額外屬性存儲在它自己的表中。當您使用實體類時,您將加入對所有屬性的訪問。

相關問題