2012-01-22 3 views
1

I의 하바 관계 다 대다 제품 엔티티 및 기능 엔티티 제품 엔티티와 :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을 사용하는 경우 I는 기능을 삭제하기위한 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();