user3241334
user3241334

Reputation: 157

Abstract database entity with doctrine

Symfony 3 with Doctrine.

I have a Bundle called "MainBundle" that exists in multiple Symfony Projects (P1, P2 and P3). The MainBundle contains different Entities, for example "AbstractColor.php".

/*** AbstractColor.php ***/

/**
 * @ORM\Entity
 * @ORM\Table(name="color")
 */
class AbstractColor
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string", length=7)
     */
    protected $code;

    /* ... getter and setter ... */
}

I want to use the color entity in P1, P2 and P3, but in P3 i want to add a new field "name". For this i create a new Entity in P3 "Color.php":

/*** Color.php ***/

/**
 * @ORM\Entity
 * @ORM\Table(name="color")
 */
class Color extends \MainBundle\AbstractColor
{    
    /**
     * @ORM\Column(type="string", length=100)
     */
    protected $name;

    /* ... getter and setter ... */
}

P3 File Structure:

My problem

The code above doesn't work, because i define the table "color" several times. I also tried doctrines "Mapped Superclass", but then i can't use OneToMany associations.

Is there a good way to solve my problem? Thank you!

Upvotes: 0

Views: 624

Answers (1)

Terenoth
Terenoth

Reputation: 2598

Use Single Table Inheritance instead of MappedSuperclass, check here for documentation : http://doctrine-orm.readthedocs.org/projects/doctrine-orm/en/latest/reference/inheritance-mapping.html#single-table-inheritance

Basically, change annotations to your AbstractColor:

/**
 * @Entity
 * @InheritanceType("SINGLE_TABLE")
 * @DiscriminatorColumn(name="type", type="string")
 * @DiscriminatorMap({"AbstractColor" = "AbstractColor", "Color" = "Color"})
 */
class AbstractColor

This way, tables will not interfere, and you will have a column "type" in your table "color" that will allow Doctrine to know if the entity is an instance of AbstractColor or Color.

Oh, and by the way, your class AbstractColor is not abstract at all, that was pretty troubling at first. You might want to rename it or to make it abstract. :)

Upvotes: 1

Related Questions