开发者

How to convert entity leaving it id

There are some entities (Region, Country, City)开发者_高级运维 which used STI (or even CTI). How it possible convert Country to City leaving old id?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜