1

我有两个实体

评论和禁止评论

实体具有相同的字段,当一个评论被禁止时,从评论实体中删除对象并复制到 BannedComments

现在我使用这个脚本 Symfony 2 - 将实体克隆到不同的表

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

但我必须将所有变量更改为公共...

有更好的方法来复制内容吗?

我尝试使用克隆

$BannedComments = new BannedComments();
$BannedComments = clone $Comments;
$em->persist($BannedComments);

但是保存在评论中而不是在 BannedComments 中,因为当我克隆评论时,BannedComments 是评论的实体

4

1 回答 1

1

在我看来,这是一个非常具体的用例。评论实体有很多属性吗?如果没有,您可以编写一个特殊函数来接收一个 Comment 对象并返回一个 BannedComment 对象。

使用 getter 和 setter 来避免将它们公开。

如果您坚持使用泛型方法,请使用方法调用而不是属性访问,但有时泛型方法有点矫枉过正,而且对于具体的、非重复的用例来说是浪费时间。

于 2013-11-07T19:10:03.457 回答