首页 > 解决方案 > Symfony - 通过ID将一个对象的所有值克隆到另一个对象上?

问题描述

我陷入了巨大的混乱。

我正在尝试编写一个应该接收 user_id 并检查是否有附加到该用户的配置文件更改请求的方法。

如果有(用户表中的字段 change_request 设置为 true),则应应用更改请求 -> 应将更改请求表中该 ID 的所有用户数据字段移至该用户表。

我的服务

public function getUserApplyChangeRequest($id)
{
    $a =$this->getUserRepository()->find($id);
    $b =$this->getChangeProfileRequestRepository()->find($id);

    $b = clone $a;

    $this->em->persist($b);
    $this->em->flush();
}

我的控制器..

public function userApplyChangeRequestAction($changeRequest)
{

    $this->requirePostParams(['user_id']);

    if ($changeRequest === 1){
    $applyChange = $this->get('user')->getUserApplyChangeRequest($this->getUser());
    }

    return $this->success();
}

我需要帮助,因为我被困住了,真的不知道用这行代码做什么,但我举了一个例子来说明我想要发生的事情。

标签: phpapisymfony

解决方案


如果只有五个,最简单的方法是自己设置属性:

public function getUserApplyChangeRequest($id)
{
    $a =$this->getUserRepository()->find($id);
    $b =$this->getChangeProfileRequestRepository()->find($id);

    $a->setPropertyOne($b->getPropertyOne());
    $a->setPropertyTwp($b->getPropertyTwo());

    $this->em->persist($a);
    $this->em->flush();
}

其他选项是使用原则获取更改对象的所有属性并以这种方式调用 getter/setter(未经测试,确保添加 NULL 检查并跳过 ID 字段):

$props = $em->getClassMetadata(get_class($b))->getColumnNames();
foreach($props as $prop){
    //get value from B
    $reflectionMethod = new ReflectionMethod(get_class($b),'get'.ucfirst($prop));
    $value = $reflectionMethod->invoke($b);

    //set value in A
    $reflectionMethod = new ReflectionMethod(get_class($a),'set'.ucfirst($prop));
    $reflectionMethod->invoke($a, $value);
}

推荐阅读