如何在foreach循环中将方法替换为变量?

时间:2019-10-03 14:44:39

标签: php symfony variables foreach doctrine

这是fieldsData:

{#1292 ▼
  +"167d580ee0": 1
  +"20fc1f0271": 2
  +"585687a0fb": 3
}

我的控制器:

 foreach ($fieldsData as $uuid => $fieldId) {

  $fieldsEntity = $this->getDoctrine()->getRepository($en)->findOneBy(['id' => $fieldId]);
  $name = $fieldsEntity->getName();

  $entity = new $EntityName();

  $entity->setName("test");
  $entity->setAge("test");
  $entity->setJob("test");

 }

 $this->em->persist($entity);
 $this->em->flush();

到目前为止,效果很好。但是我想用这样的变量替换该方法:

 foreach ($fieldsData as $uuid => $fieldId) {

   $fieldsEntity = $this->getDoctrine()->getRepository($en)->findOneBy(['id' => $fieldId]);
   $name = $fieldsEntity->getName();

   $entity = new $EntityName();
   $func = 'set' . $name;
   $entity->$func("test");

 }

 $this->em->persist($entity);
 $this->em->flush();

但是我现在收到错误消息:

  

SQLSTATE [23000]:违反完整性约束:1048列“名称”   不能为空

我不会理解,因为当我转储$name时会得到输出:

name
age
job

2 个答案:

答案 0 :(得分:2)

您将在每次迭代中创建一个新的$entity

您说转储$name时得到以下输出:

name
age
job

这意味着,最后次迭代将得出以下结果:

foreach ($fieldsData as $uuid => $fieldId) {

   $fieldsEntity = $this->getDoctrine()->getRepository($en)->findOneBy(['id' => $fieldId]);
   $name = $fieldsEntity->getName();

   $entity = new $EntityName();
   $func = 'set' . 'job';
   $entity->$func("test");

 }

 $this->em->persist($entity); // you didn't set name in $entity, but only job.
 $this->em->flush();

移动$entity = new $EntityName(); 之前 foreach

答案 1 :(得分:1)

为此任务使用属性访问器:

use Symfony\Component\PropertyAccess\PropertyAccess;

$propertyAccessor = PropertyAccess::createPropertyAccessor();
$propertyAccessor->setValue($entity, $name, 'test');

更多信息:https://symfony.com/doc/current/components/property_access.html#usage