2017-05-08 8 views
0

に多くのによって作成されたテーブルに対するクエリの構築そして、私の第二のエンティティに:symfonyの私は第3回のテーブルに多くの関係に多くを接続2つの実体を持っている、と私は、製品のIDのすべての色を取得したい多くの関係

/** 
* @var ArrayCollection 
* 
* @ORM\ManyToMany(targetEntity="AppBundle\Entity\Product", mappedBy="colors") 
*/ 
private $products; 

は、これが私のクエリです:(私はいくつかのジョイン作るしようとしていたが、それを動作させるカント)

class ProductRepository extends \Doctrine\ORM\EntityRepository 
{ 
    public function getColors($id) 
    { 
     $query = $this->createQueryBuilder('p') 
      ->join('AppBundle\Entity\Color', 'c') 
      ->where('c.product_id = :id') 
      ->setParameter('id', $id) 
      ->getQuery() 
      ->getResult(); 

     return $query; 
    } 
} 

私はこのエラーを得た:私は理解して

[Semantical Error] line 0, col 85 near 'product_id =': Error: Class AppBundle\Entity\Color has no field or association named product_id

を、この作品を作るための方法を考えることはできません。

答えて

1

Symfonyは、ManyToMany関係でマッピングされたときに、オブジェクトのエンティティ(idではない)を参照することを期待しています。試してみてください:

class ProductRepository extends \Doctrine\ORM\EntityRepository 
{ 
    public function getColors(Product $product) 
    { 
     $query = $this->createQueryBuilder('p') 
      ->join('AppBundle\Entity\Color', 'c') 
      ->where('c.product = :product') 
      ->setParameter('product', $product) 
      ->getQuery() 
      ->getResult(); 

     return $query; 
    } 
} 

もちろんこの関数の呼び出しを変更する必要があります。

また、エンティティ内のゲッター関数を使用してクエリ作成をスキップすることもできます。 symfonyが自動的にクエリを実行します。

// class Product 

private $colors; // as you have it set up already 

/** 
* @return ArrayCollection|Color[] 
*/ 

public function getColors() 
{ 
    return $this->colors; 
} 
+0

私はこれを前にしてgetColors関数を持っていましたが、代わりにそれを使用する代わりに、黒い魔法を構築しようとしていました。 –

関連する問題