Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
696 views
in Technique[技术] by (71.8m points)

php - Symfony 2 - Clone entity to different table

I am trying to clone an entity-object to a different table in Symfony 2 / Doctrine. Any idea how to do this?

After retrieving the object from the database I can clone it like this:

$newobject = clone $oldbject;

This gives me a new object, which I can persist as a new record to the same table in the database. Actually I dont want to do this. I want to store the object as it is to a different table in the database. But to do this, I would have to change the parent entity, right? How to achieve this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

But then you're not really cloning an entity. In fact, you want a different entity. What do the two entities look like? Do they have the same fields? You could do something like this:

$oldEntity = $oldEntity;
$newEntity = new NewEntity();
$oldReflection = new ReflectionObject($oldEntity);
$newReflection = new ReflectionObject($newEntity);

foreach ($oldReflection->getProperties() as $property) {
    if ($newReflection->hasProperty($property->getName())) {
        $newProperty = $newReflection->getProperty($property->getName());
        $newProperty->setAccessible(true);
        $newProperty->setValue($newEntity, $property->getValue($oldEntity));
    }
}

This is untested - and may have an error or two, but this should allow all properties to be copied from one object to another (assuming the properties have the same name on both objects).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...