通过关系发现了一个新的实体

A new entity was found through the relationship

错误信息:

A new entity was found through the relationship 'AppBundle\Entity\Tarifa#pesos' that was not configured to cascade persist operations for entity: AppBundle\Entity\TarifaPeso@0000000072d3bd4300000000232470d3. To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity or configure cascade persist this association in the mapping for example @ManyToOne(..,cascade={"persist"}). If you cannot find out which entity causes the problem implement 'AppBundle\Entity\TarifaPeso#__toString()' to get a clue.

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(),
    ));
}

我错过了什么?真的很累...请帮忙?

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

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

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

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