How (if possible at all) do you change the entity type with Doctrine2, using it's Class Table Inheritance?
Let's say I have a Person
parent class type and two inherited types Employe
and Client
. My system allows to create a Person and specify it's type - that's fairly easy to implement - but I'd also like to be able to change the person from an Employe to a Client, while maintaining the Person
-level information (it's id and other associated records).
Is there a simple way to do this with Doctrine2?
I was looking for this behaviour yesterday also.
In the end, after speaking with people in #doctrine on freenode, I was told that it is not possible.
If you want to do this, then you have to go through this:
Upgrading a User
Employee
table for this inheritance.Removing Inheritance
Likewise if you want to remove inheritance, you have to..
Employee
table. (Yes you have to delete it, just change the discrimator coumn is not sufficient).This might be 7 months late, but it is at least the correct answer for anything else looking to suport such a feature.
PHP doesn't have support for object casting, so Doctrine doesn't support it. To workaround the problem I write this static method into parent classes:
You can create this method in class Person and use it to cast from Employe to Client and viceversa:
Now, if you want, you can remove the $employe entity.
In Doctrine2, when you have your parent entity class,
Person
set as:and sub classes such as
Client
set as:when you instantiate
Person
as:Doctrine2 checks your
@DiscriminatorMap
statement (above) for a corresponding mapping toPerson
and when found, creates a string value in the table column set in@DiscriminatorColumn
above.So when you decide to have an instance of
Client
as:Following these principles, Doctrine2 will create an instance for you as long as you have declared the parameters in the
@DiscriminatorMap
. Also an entry will be made on thePerson
table, in the discr column to reflect that type of entity class that has just been instantiated.Hope that helps. It's all in the documentation though
You could do something like this though:
This Trait can be used on your Repository class:
There still might be some extra work you need to put in, like clearing values in fields that are only present on one of your sub-classes