Reputation: 5074
In my project, I have a bundle which works fine, now I needed to create a second bundle. One entity of my second bundle has the same name as an entity of my first bundle+same fields except it must have two extra fields, and I need the two bundles two work on the same table in the database. How can I extend from an entity in order to add fields and to keep extended ones?
Knowing that I tried the classic inheritence, but I got a beautiful error from doctrine
[Doctrine\DBAL\Schema\SchemaException]
The table with name 'postgres.article' already exists.
No surprise here because the table does exist, How do I do to get doctrine to update it and not try to create it?
Upvotes: 0
Views: 944
Reputation: 7715
This is called Class Table Inheritance. You can have a parent entity and child entities that extend it. Your additional fields are stored in your child's table and the primary key is linked to the parent table.
The following is a basic example from some of my existing code, you can modify it for your purposes. I have excluded the accessor methods.
Pitfall! When using CTI you must make your properties protected
, setting them to private will not allow them to be shared.
Parent Class
/**
* 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;
}
Child Table
/**
* 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;
}
In this example you would have an item table and a physical_item table. All the properties of item are stored there and the extra properties of physical_item are stored in it's own table. When you use the Entity class you will have joined access to all properties.
Upvotes: 1