【问题标题】:How can I store data in Array Collection with doctrine (Symfony 4)?如何使用学说(Symfony 4)将数据存储在数组集合中?
【发布时间】:2019-02-04 16:42:32
【问题描述】:

我的控制器:

            /**
            * @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;

            }

错误信息:

“产品组”类不存在

【问题讨论】:

    标签: symfony doctrine entity arraycollection


    【解决方案1】:

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

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

    也许你应该使用 addProductgroup()。

    如果 $argsId 是一个 id 数组,则应该获取每个 id 的引用,并将 ghost 对象添加到 ArrayCollection。

    【讨论】:

    • 谢谢。是的,“添加”是正确的。请参阅下面的工作解决方案
    【解决方案2】:

    工作解决方案:

         /**
            * @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;
    
            }
    

    【讨论】:

    • 我很高兴你找到了解决方案,但没有任何解释或上下文,这个答案对其他人没有帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-16
    • 2021-10-06
    相关资源
    最近更新 更多