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個選擇查詢。也許我讓這個任務錯了?
** **答:請參考我在http作出的回答:// stackoverflow.com/a/35445060/2423563 – SudarP