How to change and entity type in Doctrine2 CTI Inheritance

前端 未结 4 1031
走了就别回头了
走了就别回头了 2020-12-17 18:38

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

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-17 18:56

    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

提交回复
热议问题