【问题标题】:Copy same value From Entity to Entity将相同的值从实体复制到实体
【发布时间】:2013-11-07 17:52:17
【问题描述】:

我有两个实体

评论和禁止评论

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

现在我使用这个脚本 Symfony 2 - Clone entity to different table

$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 是评论的实体

【问题讨论】:

  • 您为什么不使用带有布尔值的Comment 实体将评论设置为禁止

标签: php symfony


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-11
    • 1970-01-01
    • 1970-01-01
    • 2019-02-13
    • 1970-01-01
    • 2017-12-23
    • 1970-01-01
    相关资源
    最近更新 更多