我的控制器:
/**
* @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;
}
错误消息:
类"产品组"不存在
我不能告诉你为什么会出现类错误,但你不能将实体对象传递给需要 ArrayCollection 的方法,这里:
/* args is not an ArrayCollection */
$args = $entityManager->getReference($connect , $argsId);
$entity->setProductgroup($args);
也许你应该使用 addProductgroup((。
如果 $argsId 是一个 id 数组,你应该获取每个 id 的引用,并将 ghost 对象添加到 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;
}