【问题标题】:How to backup an ArrayCollection before removing element?如何在删除元素之前备份 ArrayCollection?
【发布时间】:2018-08-20 07:20:43
【问题描述】:

所以我想存储 ArrayCollection 值,将其删除,然后在另一个实体中重用它。 但似乎该值是通过引用传递的,所以当它未设置时,存储的值也未设置。

$children = $role->getChildren();
var_dump(count($children)); // int(1)
$role->removeAllChildren();
var_dump(count($children)); // int(0)

/** **/

/**
 * @return Role
 */
public function removeAllChildren()
{
    foreach ($this->children as $child) {
        $this->removeChild($child);
    }

    return $this;
}


/**
 * @param Role $child
 *
 * @return Role
 */
public function removeChild(Role $child)
{
    if ($this->hasChild($child)) {
        $this->children->removeElement($child);

        // this calls unset($this->elements[$key]);
    }

    return $this;
}

那么有没有办法在我删除之前存储 arrayCollection 值?

顺便说一句,我正在使用 Symfony 3.4。

【问题讨论】:

  • 根据您想对集合做什么,$children = clone $role->getChildren(); 应该可以工作。 (孩子必须是可克隆对象)
  • 是的,工作。我什至不知道为什么我没有尝试。再次感谢。

标签: symfony unset arraycollection


【解决方案1】:

ArrayCollection 是一个对象,您可以在此对象上使用简单的$chilrenCopy = clone $obj->getChildren();,它将复制该对象并分配给新的引用。也有可能使用名为Memento的设计模式

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-21
    • 2011-03-09
    • 2022-12-17
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多