Bhaktaraz

Web Enthusiastic, Nature Lover

Doctrine 2 Single Class Inheritance (SCI)

Single Class Inheritance is an inheritance mapping strategy where all classes of a hierarchy are mapped to a single database table. In order to distinguish which row represents which type in the hierarchy a so-called discriminator column is used.

Things to note:

  • The @InheritanceType, @DiscriminatorColumn and @DiscriminatorMap must be specified on the topmost class that is part of the mapped entity hierarchy.
  • The names of the classes in the discriminator map do not need to be fully qualified if the classes are contained in the same namespace as the entity class on which the discriminator map is applied.

<?php

namespace Entities;

/**
* @Entity
* @Table(name=”pets”)
* @InheritanceType(“SINGLE_TABLE”)
* @DiscriminatorColumn(name=”pet_type”, type=”string”)
* @DiscriminatorMap({“cat” = “Cat”, “dog” = “Dog”})
*/
class Pet
{
/** @Id @Column(type=”integer”) @generatedValue */
private $id;

/** @Column(type=”string”, length=300) */
private $name;

/** @ManyToOne(targetEntity=”User”, inversedBy=”id”) */
private $owner;
}

/** @Entity */
class Dog extends Pet
{
/** @Column(type=”string”, length=50) */
private $kennels;
}

/** @Entity */
class Cat extends Pet
{
/** @Column(type=”string”, length=50) */
private $cattery;
}

/**
* @Entity
* @Table(name=”users”)
*/
class User
{
/** @Id @Column(type=”integer”) @generatedValue */
private $id;

/** @Column(length=255, nullable=false) */
private $name;

/** @OneToMany(targetEntity=”Pet”, mappedBy=”owner”) */
private $pets;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.