2012-01-22 15 views
1

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テーブルを更新するにはどうすればよいですか?また、Product_Featureからすべての機能を製品の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を使用する場合、私は削除する機能の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();