php - 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();
}
我需要帮助,因为我被困住了,真的不知道用这行代码做什么,但我举了一个例子来说明我想要发生的事情。
解决方案
如果只有五个,最简单的方法是自己设置属性:
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);
}
推荐阅读
- postgresql - Rails 5 和 Postgres - 我可以使用“?” 在字段名称中?
- neo4j - 使用可变 MATCH 标签动态创建 Neo4j/Cypher 关系
- objective-c - 从首选项窗格注册登录项的最佳方法?
- javascript - Image resize using JAVAScript returning empty image
- javascript - 如何在带有窗口的对象中创建新值
- android-studio - 新手机上未安装应用程序
- c# - Drag and Drop from Explorer not working for C# Winforms App
- r - R: object of type 'closure' is not subsettable (Rshiny problem)
- python - OpenCV copying a list of pixels from one image to another
- c# - Multitasking with windows service