我在2个实体之间有一个OneToOne关系。一个分子和一个ConcGenotox(关于遗传毒性的结论)。
我来自一个页面,其中显示了关于一个Molecule的所有图像,并且Molecule的id在地址栏中。
有一个按钮可以编辑关于这个分子的新的ConcGenotox,它始终位于地址栏中。
我的问题是:当添加新的ConcGenotox时,如何自动添加来自分子的id在ConcGenotox的id_molecule关系中?
ConcGenotox实体:
class ConcGenotox
{
/**
* @var \Molecule
*
* @ORM\OneToOne(targetEntity="Molecule")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="id_molecule", referencedColumnName="id")
* })
*
*/
private $idMolecule;
分子实体:
class Molecule
{
/**
* @ORM\OneToOne(targetEntity="NcstoxBundle\Entity\ConcGenotox", mappedBy="idMolecule")
*/
private $concGenotox;
CONTROLER:
/**
* Creates a new concGenotox entity.
*
* @Route("/new/{id}", name="concgenotox_new")
* @Method({"GET", "POST"})
*/
public function newAction(Request $request, $id)
{
$concGenotox = new Concgenotox();
$form = $this->createForm('NcstoxBundle\Form\ConcGenotoxType', $concGenotox);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
var_dump($id);
$concGenotox->setIdMolecule($id);
$em->persist($concGenotox);
$em->flush();
return $this->redirectToRoute('concgenotox_show', array('id' => $concGenotox->getId()));
}
return $this->render('concgenotox/new.html.twig', array(
'concGenotox' => $concGenotox,
'form' => $form->createView(),
'id' => $id,
));
}
我尝试->setIdMolecule($id)
,但它给了我一个错误:
Expected value of type "NcstoxBundle\Entity\Molecule" for association field "NcstoxBundle\Entity\ConcGenotox#$idMolecule", got "string" instead.
答案 0 :(得分:2)
试试这个:
$em = $this->getDoctrine()->getManager();
$molecule = $em->getRepository('YourBundle:Molecule')
->find($id);
$concGenotox->setIdMolecule($molecule);
您需要将实体设置为Id
答案 1 :(得分:1)
关系属性应该是实体,而不是id。
变化:
class ConcGenotox
{
/**
* @var \Molecule
*
* @ORM\OneToOne(targetEntity="Molecule")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="id_molecule", referencedColumnName="id")
* })
*
*/
private $idMolecule;
为:
class ConcGenotox
{
/**
* @var \Molecule
*
* @ORM\OneToOne(targetEntity="Molecule", cascade={"persist"})
*/
private $molecule;
并将您的操作更改为:
/**
* Creates a new concGenotox entity.
*
* @Route("/new/{molecule}", name="concgenotox_new")
* @Method({"GET", "POST"})
*/
public function newAction(Request $request, Molecule $molecule)
{
$concGenotox = new Concgenotox();
$form = $this->createForm(ConcGenotoxType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$concGenotox = $form->getData();
$molecule->setConcGenotox($concGenotox);
$this->getDoctrine()->getManager()->flush();
return $this->redirectToRoute('concgenotox_show', array('id' => $concGenotox->getId()));
}
return $this->render('concgenotox/new.html.twig', array(
'concGenotox' => $concGenotox,
'form' => $form->createView(),
'id' => $id,
));
}