Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change and entity type in Doctrine2 CTI Inheritance

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?

like image 641
Jimmy Avatar asked May 09 '11 14:05

Jimmy


2 Answers

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

  1. Grab the Person Entity.
  2. Update the discrimator column so that it is no longer a 'person' and change it to 'employee'
  3. Create a corresponding row inyour Employee table for this inheritance.

Removing Inheritance

Likewise if you want to remove inheritance, you have to..

  1. Grab the Person Entity.
  2. Update the discrimnator column so that it is no longer an 'employee' and change it to a 'person'.
  3. Delete the corresponding row in your 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.

like image 87
Layke Avatar answered Oct 23 '22 13:10

Layke


You could do something like this though:

This Trait can be used on your Repository class:

namespace App\Doctrine\Repository;

trait DiscriminatorTrait
{
    abstract public function getClassMetadata();

    abstract public function getEntityManager();

    private function updateDiscriminatorColumn($id, $class)
    {
        $classMetadata = $this->getClassMetadata();

        if (!in_array($class, $classMetadata->discriminatorMap)) {
            throw new \Exception("invalid discriminator class: " . $class);
        }

        $identifier = $classMetadata->fieldMappings[$classMetadata->identifier[0]]["columnName"];

        $column = $classMetadata->discriminatorColumn["fieldName"];
        $value = array_search($class, $classMetadata->discriminatorMap);

        $connection = $this->getEntityManager()->getConnection();

        $connection->update(
            $classMetadata->table["name"],
            [$column => $value],
            [$identifier => $id]
        );
    }
}

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

like image 36
murtho Avatar answered Oct 23 '22 14:10

murtho