在OneToMany关系中插入Symfony2中的外键

时间:2014-09-11 07:02:55

标签: symfony doctrine

我在向数据库添加数据时遇到问题。我在OneToMany关系中有两个实体InternalDocumentInternalDocumentProduct。 在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(),
    ));
}

0 个答案:

没有答案