1

Is it possible to have a php class which extends a doctrine entity and to persist it ?

example:

/** * @Entity */ class A { /** * @ORM\ManyToMany(targetEntity="C", mappedBy="parents") */ protected $children; } class B extends A { ... } class C { /** * @ORM\ManyToMany(targetEntity="A", inversedBy="children") */ protected $parents; } $b = new B(); $em->persist($b); 

1 Answer 1

3

Yes it's possible, this is called inheritance mapping, but the child class has to be explicitly declared as @Entity and its mapping has to be explicitly defined as well (if the child class adds extra properties).

The most common form of inheritance mapping is single table inheritance, here is an example of such mapping from the Doctrine manual:

namespace MyProject\Model; /** * @Entity * @InheritanceType("SINGLE_TABLE") * @DiscriminatorColumn(name="discr", type="string") * @DiscriminatorMap({"person" = "Person", "employee" = "Employee"}) */ class Person { // ... } /** * @Entity */ class Employee extends Person { // ... } 
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for your answer :) Unfortunately we can not use inheritance mapping because we need to have associations to the parent class. Inheritance mapping does not work well with association in the parent class...
What do you mean by "association in the parent class"? Please give an example!
That should work equally well; what may require some work in your domain model, is to keep consistency. That is, A::addChild() should call C::addParent(), and/or vice-versa. Doctrine will not do this magic for you. But this is outside the scope of your original question, for which the answer is yes, you can.
docs.doctrine-project.org/projects/doctrine-orm/en/latest/… Doctrine documentation says: There is a general performance consideration with Single Table Inheritance: If the target-entity of a many-to-one or one-to-one association is an STI entity, it is preferable for performance reasons that it be a leaf entity in the inheritance heirarchy, (ie. have no subclasses). Otherwise Doctrine CANNOT create proxy instances of this entity and will ALWAYS load the entity eagerly.
Normally it's not a big problem because if I load A or B, C will be load. Because C has a proxy nothing else will be load. But in my Schema I also have a OneToMany relation between two B. So if I load a B object, which does not have any Proxy, all B will be loaded plus all C. It's a big performance issue...
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.