我在向数据库添加数据时遇到问题。我在OneToMany关系中有两个实体InternalDocument
和InternalDocumentProduct
。
在InternalDocument
:
/**
* @ORM\OneToMany(targetEntity="InternalDocumentProduct", mappedBy="document", cascade={"all"})
**/
protected $products;
在InternalDocumentProduct
/**
* @ORM\ManyToOne(targetEntity="InternalDocument", inversedBy="products")
* @ORM\JoinColumn(name="document_id", referencedColumnName="id")
* */
protected $document;
当我创建新InternalDocument
时,我也需要插入InternalDocumentProduct
。但是当我调用persist()
方法时,InternalDocumentProduct
会在没有document_id
字段的情况下保存。它是空的。这是createForm()
中的InternalDocumentController
方法:
/**
* Creates a new InternalDocument entity.
*
*/
public function createAction(Request $request)
{
$entity = new InternalDocument();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
$em = $this->getDoctrine()->getManager();
if ($form->isValid()) {
$em->persist($entity);
$em->flush();
$em = $this->getDoctrine()->getManager();
foreach($entity->getProducts() as $p) {
$em->persist($p);
}
$em->flush();
return $this->redirect($this->generateUrl('acme_warehouse_documents'));
}
return $this->render('AcmeWarehouseBundle:InternalDocument:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
任何人都可以帮助我吗?
编辑: 我解决了这个问题。我修改了createAction方法:
/**
* Creates a new InternalDocument entity.
*
*/
public function createAction(Request $request)
{
$entity = new InternalDocument();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
$em = $this->getDoctrine()->getManager();
if ($form->isValid()) {
foreach($entity->getProducts() as $p) {
$p->setDocument($entity);
}
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('acme_warehouse_documents'));
}
return $this->render('AcmeWarehouseBundle:InternalDocument:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}