Ajouve
Ajouve

Reputation: 10089

Modeling of inherited entities in Symfony2

I have an Entity called Type, type have data1, data2 and data3 as attribute. I'd like to have Type1 which extends Type and Type2 which extends Type too

For exemple

Class Type
{
    private $data1;
    private $data2;
    private $data3;   
}

Class Type1 extends Type
{
    private $data4;
}

Class Type2 extends Type
{
    private $data5;
}

I'd like to get this in my Symfony entities and this must works with Doctrine.

Upvotes: 0

Views: 61

Answers (1)

Carlos Vergara
Carlos Vergara

Reputation: 3622

Considering your example, use the following Doctrine annotations:

use Doctrine\ORM\Mapping AS ORM;

/**
 * @ORM\Entity
 * @ORM\InheritanceType("JOINED")
 * @ORM\DiscriminatorColumn(name="Type_Disc", type="string")
 * @ORM\DiscriminatorMap({"type1" = "Type1", "type2" = "Type2"})
 */
Class Type
{
    /**
    * @ORM\Column(name="data1", type="integer")
    */
    private $data1;

    /**
    * @ORM\Column(name="data2", type="integer")
    */
    private $data2;

    /**
    * @ORM\Column(name="data3", type="integer")
    */
    private $data3;   
}

/**
* @ORM\Entity
*/
Class Type1 extends Type
{
    /**
    * @ORM\Column(name="data4", type="integer")
    */
    private $data4;
}

/**
* @ORM\Entity
*/
Class Type2 extends Type
{
    /**
    * @ORM\Column(name="data5", type="integer")
    */
    private $data5;
}

As extra information, you need something called a "discriminator column" (here called Type_Disc), so the ORM can discriminate on the type of entity. You don't have to map it to an entity value, but it has to exist in your schema. In the discriminator map you tell what values the classes will be mapped into the discriminator column. For instance, in this example Type1 will be mapped to type1 in Type_Disc. You could also use numbers, in which case it would be something like this:

 /**
 ...
 * @ORM\DiscriminatorColumn(name="Type_Disc", type="integer")
 * @ORM\DiscriminatorMap({0 = "Type1", 1 = "Type2"})
 */

Please keep in mind the schemas have to be something like this, using a SQL pseudolanguage:

CREATE TABLE Type1 (
    id int not null primary key autoincrement(1,1), /*This has to be defined somewhere in your entity*/
    Type_Disc nvarchar(50) not null,
    data1 integer not null,
    data2 integer not null,
    data3 integer not null
)

CREATE TABLE Type2 (
    id int not null primary key,
    data4 integer not null,
    foreign key (id) references Type1(id)
)

CREATE TABLE Type3 (
    id int not null primary key,
    data5 integer not null,
    foreign key (id) references Type1(id)
)

Upvotes: 1

Related Questions