Orm Doctrine2更新多对多关系
我与产品实体和特征实体有多对多的关系 产品实体:Orm Doctrine2更新多对多关系,orm,symfony,doctrine-orm,Orm,Symfony,Doctrine Orm,我与产品实体和特征实体有多对多的关系 产品实体: /** * @ORM\ManyToMany(targetEntity="Feature") * @ORM\JoinTable(name="Product_Feature", * joinColumns={@ORM\JoinColumn(name="Product_id", referencedColumnName="id")}, * inverseJoinColumns={@ORM\JoinColumn(name="F
/**
* @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时,我得到一个错误:
功能=:功能”:错误:无效的PathExpression。
应为StateFieldPathExpression或SingleValuedAssociationField
如何更新产品功能表?此外,我无法按产品id从产品功能中删除所有功能。我用下一种方法更改了控制器:
$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,我需要两个查询来删除功能和插入新功能。但是这里我需要两个select查询。也许是我把这个任务搞错了?你做得不对。您应该阅读文档的本章:。您应该在产品类的$features字段中添加一个“inversedBy”关键字 当您具有双向多对多关系时,通常的方法是:
$product->getFeatures()->add($feature); // Or $product->setFeatures($features);
$feature->getProducts()->add($product);
$em->persist($product);
$em->persist($feature);
$em->flush();
答:请参考我在