How to convert entity leaving it id

眉间皱痕 提交于 2019-12-10 20:44:33

问题


There are some entities (Region, Country, City) wich used STI (or even CTI). How it possible convert Country to City leaving old id?


回答1:


This is not supported in Doctrine 2 because type casting user objects is not supported by PHP.

With that said, Doctrine uses the discriminator column to determine what type of object to hydrate. If you change the value of the discriminator column in the database with a SQL UPDATE, the object type will be changed the next time the object is loaded. This works for STI, but CTI would be more complicated.




回答2:


It may not be possible by standard using Doctrine, but you can work around it. If you use the Class Metadata you can select your discriminator column.

Take a look at the Trait that I've created to solve the problem within my app:

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]
        );
    }
}

I do have to warn you though, when your sub-classes have (a lot of) extra fields you will need to fill or clear them manually afterwards.



来源:https://stackoverflow.com/questions/6263332/how-to-convert-entity-leaving-it-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!