【问题标题】:A new entity was found through the relationship通过关系发现了一个新实体
【发布时间】:2016-06-30 12:48:08
【问题描述】:

错误信息:

通过关系发现了一个新实体 'AppBundle\Entity\Tarifa#pesos' 未配置为级联 实体的持久化操作: AppBundle\Entity\TarifaPeso@0000000072d3bd4300000000232470d3。解决 这个问题:要么显式调用 EntityManager#persist() 未知实体或配置级联在 映射例如 @ManyToOne(..,cascade={"persist"})。如果你不能 找出导致问题的实体实施 'AppBundle\Entity\TarifaPeso#__toString()' 来获得线索。

Tarifa.php

/**
 * @ORM\OneToMany(targetEntity="TarifaPeso", mappedBy="tarifa")
 */
private $pesos;

TarifaPeso.php

/**
 * @ORM\ManyToOne(targetEntity="Tarifa", inversedBy="pesos", cascade={"persist"})
 * @ORM\JoinColumn(name="tarifa_id", referencedColumnName="id")
 */
private $tarifa;

TarifaType.php

        ->add('pesos', CollectionType::class, array(
            'entry_type'   => TarifaPesoType::class,
            'allow_add'    => true,
            'allow_delete' => true,
            'by_reference' => false
        ))

控制器...

public function newAction(Request $request)
{
    $tarifa = new Tarifa();

    $form = $this->createForm('AppBundle\Form\TarifaType', $tarifa);

    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {

        $entityManager = $this->getDoctrine()->getManager();
        $entityManager->persist($tarifa);
        $entityManager->flush();

        $this->addFlash('success', 'project.created_successfully');

        return $this->redirectToRoute('admin_post_index');
    }

    return $this->render('admin/tarifas/new.html.twig', array(
        'form' => $form->createView(),
    ));
}

我错过了什么?真的累死了……请帮忙?

【问题讨论】:

  • 您自己处理表单提交吗?
  • 对不起,我忘了添加控制器代码,我已经更新了。我用 'merge' 更改了 'em->persist' 并且它可以工作,但它不存储嵌入类(TarifaPeso)......

标签: forms symfony doctrine embed


【解决方案1】:

您应该将 cascade={"persist"} 注释从 TarifaPeso::tarifa 移动到 Tarifa::pesos 属性。或者,您可以显式保留您从表单中获得的所有 pesos

$entityManager->persist($tarifa); 
foreach ($tarifa->getPesos() as $peso) {
     $entityManager->persist($peso);
}
$entityManager->flush();

【讨论】:

  • 太棒了!它将数据保存在 TarifaPeso 表中,但不保存 TarifaPeso 表中的 tarifa_id (它没有保存外键,只有其他两个字段),我还需要添加什么吗?求你的帮助!!!
【解决方案2】:

好的,解决了,现在它将 Tarifa id 存储在 TarifaPeso 表中。错误是我从 AddPeso 方法中删除了该行:

public function addPeso(\AppBundle\Entity\TarifaPeso $pesos)
{
    $this->pesos[] = $pesos;
    $pesos->setTarifa($this);
    return $this;
}

【讨论】:

  • 哪一个是“行”?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多