ManyToMany双向关系不保存数据

时间:2013-08-13 19:00:27

标签: symfony doctrine symfony-forms symfony-2.3

我在productproduct_details表之间存在多对多关系,从而产生第三个名为product_has_product_details的表。我做了这个代码:

ProductBundle\Entity\ProductDetail.php

/**
 * @ORM\ManyToMany(targetEntity="CategoryBundle\Entity\Category", mappedBy="pd_category")
 */
protected $category;

public function __construct() {
    $this->category = new \Doctrine\Common\Collections\ArrayCollection();
}

public function setCategory($category) {
    $this->category[] = $category;
}

CategoryBundle\Entity\Category.php

/**
 * @ORM\ManyToMany(targetEntity="ProductBundle\Entity\ProductDetail", inversedBy="category")
 * @ORM\JoinTable(name="product_detail_has_category")
 */
protected $pd_category;

public function __construct() {
    $this->pd_category = new \Doctrine\Common\Collections\ArrayCollection();
}

在我的控制器ProductDetailController.php中有以下代码:

/**
 * Handle category creation
 *
 * @Route("/pdetail/create", name="pdetail_create")
 * @Method("POST")
 * @Template("ProductBundle:ProductDetail:new.html.twig")
 */
public function createAction(Request $request) {
    $entity = new ProductDetail();
    $form = $this->createForm(new ProductDetailType(), $entity);
    $form->handleRequest($request);

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $entity->setValuesText(serialize($form->get('values_text')->getData()));
        $em->persist($entity);
        $em->flush();

        return $this->redirect($this->generateUrl('pdetail_list'));
    }

    return $this->render('ProductBundle:ProductDetail:new.html.twig', array(
                'entity' => $entity,
                'form' => $form->createView(),
    ));
}

当我发送表单时,ProductDetail的值被保存,但关系的值没有,我找不到问题的位置。我也收到了这个错误:

控制器必须返回响应(Array(product_details => Array(0 => Object(ProductBundle \ Entity \ ProductDetail),1 => Object(ProductBundle \ Entity \ ProductDetail),2 => Object( ProductBundle \ Entity \ ProductDetail)))给出)。

能帮助我吗?

1 个答案:

答案 0 :(得分:1)

如果您要显示ProductDetail->setValuesText方法,那就太好了。但无论如何,您必须创建一个新的Category对象(或者使用已有的对象)。然后做

$category = new Category();
$em->persist($category);
$productDetail->setCategory();
$em->persist($productDetail);
$em->flush();