如何使用 doctrine (Symfony 4) 将数据存储在 Array Collection 中?

How can I store data in Array Collection with doctrine (Symfony 4)?

我的控制器:

            /**
            * @Route("/row/{slug}/{connect}/{field}/{productgroup}", name="row", methods={"POST"})
            */

            public function row($slug, $connect, $field,$productgroup, Request $request) {

              $EntityName = 'App\Entity\' . ucwords($slug);
              $con = 'App\Entity\' . ucwords($connect);
              $entity = $this->getDoctrine()->getRepository($EntityName)->findOneBy(['id' => $field]);
              $entityManager = $this->getDoctrine()->getManager();
              $argsId = $productgroup;
              $args = $entityManager->getReference($connect , $argsId);
              $entity->setProductgroup($args);

              $entityManager->flush();
              $response = new Response();
              $response->send();
              return $response;

            }

错误信息:

Class 'Productgroup' does not exist

我不能告诉你为什么会出现 class 错误,但你不能将实体对象传递给需要 ArrayCollection 的方法,此处:

/* args is not an ArrayCollection */
$args = $entityManager->getReference($connect , $argsId);
$entity->setProductgroup($args); 

也许你应该使用 addProductgroup()。

如果 $argsId 是一个 ID 数组,您应该获取每个 ID 的引用,并将幽灵对象添加到 ArrayCollection。

工作解决方案:

     /**
        * @Route("/row/{entity}/{relation}/{entity_id}/{relation_id}", name="row", methods={"POST"})
        */

        public function row($entity, $relation, $entity_id, $relation_id, Request $request) {

          $entity_name = 'App\Entity\' . ucwords($entity);
          $relation_name = 'App\Entity\' . ucwords($relation);

          $entityManager = $this->getDoctrine()->getManager();
          $enity_reference = $entityManager->getReference($entity_name, $entity_id);
          $relation_reference = $entityManager->getReference($relation_name, $relation_id);

          $func = 'add'.$relation;
          $enity_reference->$func($relation_reference);
          $entityManager->persist($enity_reference);
          $entityManager->persist($relation_reference);

          $entityManager->flush();
          $response = new Response();
          $response->send();
          return $response;

        }