2012-01-22 148 views
1

我HAVA关系多到许多与产品实体和功能实体 产品实体:Doctrine2更新许多一对多关系

/** 
* @ORM\ManyToMany(targetEntity="Feature") 
* @ORM\JoinTable(name="Product_Feature", 
*  joinColumns={@ORM\JoinColumn(name="Product_id", referencedColumnName="id")}, 
*  inverseJoinColumns={@ORM\JoinColumn(name="Feature_id", referencedColumnName="id")} 
*  ) 
*/ 
private $features; 

功能实体:

/** 
* @ORM\ManyToMany(targetEntity="Product", mappedBy="features") 
* @ORM\OrderBy({"position" = "ASC"}) 
*/ 
private $products; 

ProductRepository.php:

public function updateFeatures($id, $featuresIds) 
    { 
     return $this->getEntityManager()->createQueryBuilder() 
       ->update('TestCatalogBundle:Product', 'p') 
       ->set('p.features', ':features') 
       ->where('p.id = :id') 
       ->setParameter('features', $featuresIds) 
       ->setParameter('id', $id) 
       ->getQuery() 
       ->getResult(); 
    } 

但是,当我打电话updateFeatures我得到错误:

features = :features': Error: Invalid PathExpression. StateFieldPathExpression or SingleValuedAssociationField expected

如何更新Product_Feature表?此外,我无法通过产品ID删除Product_Feature中的所有功能。
我改变了我的下一路控制器:

$em = $this->getDoctrine()->getEntityManager(); 

    $features = $em->getRepository('TestCatalogBundle:Feature')->findBy(array('id' => $featureIds)); 
    $product = $em->getRepository('TestCatalogBundle:Product')->find($id); 

    $product->getFeatures()->clear(); 
    foreach ($features as $feature) { 
     $product->addFeature($feature); 
    } 
    $em->persist($product); 
    $em->flush(); 

但是,如果使用本地的SQL我需要2个查询,删除功能,并插入新的功能。但在这里我需要2个选择查询。也许我让这个任务错了?

+0

** **答:请参考我在http作出的回答:// stackoverflow.com/a/35445060/2423563 – SudarP

回答

2

你这样做是错误的。您应该阅读本文档的这一章:Working with associations。您应该在Product类的$ features字段中添加一个“inversedBy”关键字。

当你有一个双向许多一对多的关系,通常的方式做到这一点是:

$product->getFeatures()->add($feature); // Or $product->setFeatures($features); 
$feature->getProducts()->add($product); 
$em->persist($product); 
$em->persist($feature); 
$em->flush();