inheritance - Abstract database entity with doctrine -


symfony 3 doctrine.

i have bundle called "mainbundle" exists in multiple symfony projects (p1, p2 , p3). mainbundle contains different entities, 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 , setter ... */ } 

i want use color entity in p1, p2 , p3, in p3 want add new field "name". create 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 , setter ... */ } 

p3 file structure:

  • app
  • bin
  • src
    • p3bundle
      • entity
        • color.php
  • var
  • vendor
    • mainbundle
      • entity
        • abstractcolor.php

my problem

the code above doesn't work, because define table "color" several times. tried doctrines "mapped superclass", can't use onetomany associations.

is there way solve problem? thank you!

use single table inheritance instead of mappedsuperclass, check here documentation : http://doctrine-orm.readthedocs.org/projects/doctrine-orm/en/latest/reference/inheritance-mapping.html#single-table-inheritance

basically, change annotations abstractcolor:

/**  * @entity  * @inheritancetype("single_table")  * @discriminatorcolumn(name="type", type="string")  * @discriminatormap({"abstractcolor" = "abstractcolor", "color" = "color"})  */ class abstractcolor 

this way, tables not interfere, , have column "type" in table "color" allow doctrine know if entity instance of abstractcolor or color.

oh, , way, class abstractcolor not abstract @ all, pretty troubling @ first. might want rename or make abstract. :)


Comments