Search code examples
phpdoctrine-ormdoctrine

Doctrine multi-level inheritance


I have some problem using Doctrine and inheritance in Symfony 5.

First, I have a base entity with only 2 dates (createdAt and updatedAt).

/**
 * @ORM\MappedSuperclass()
 */
class BaseEntity
{
    /**
     * @ORM\Column(type="datetime")
     */
    protected $createdAt;

    /**
     * @ORM\Column(type="datetime")
     */
    protected $updatedAt;
}

Next, I have another class extending the BaseEntity (for example "MyClass1").

/**
 * @ORM\Entity(repositoryClass=MyClass1Repository::class)
 * @ORM\MappedSuperclass()
 */
class MyClass1 extends BaseEntity
{
    /* Some properties */
}

Finally, I have my class extending MyClass1 (for example "MyClass2").

/**
 * @ORM\Entity(repositoryClass=MyClass2Repository::class)
 */
class MyClass2 extends BaseEntity
{
    /* Some properties */
}

When I migrate my database (make:migration), Doctrine creates 2 tables :

  • myclass1
  • myclass2

Can you tell me where I am wrong ? I'd have only 1 table : myclass2.


Solution

  • The mistake is in the MyClass1 definition. From the Doctrine documentation about inheritance mapping.

    A mapped superclass is an abstract or concrete class that provides persistent entity state and mapping information for its subclasses, but which is not itself an entity. Typically, the purpose of such a mapped superclass is to define state and mapping information that is common to multiple entity classes.

    A Mapped superclass itself is not an entity, by adding the @Entity next to the @MappedSuperclass you're effectively making it an entity. The mapped superclass should not be an entity and is not query-able.