我与产品实体和功能实体的多对多关系 产品实体:
/**
* @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':错误:无效的PathExpression。 StateFieldPathExpression或SingleValuedAssociationField预期
如何更新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 :(得分: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();