2011-09-19 73 views
2

我有产品和颜色之间的多对多关系。主义实体findBy多对多

我想要做的是通过它们的颜色找到产品。

如)

$colours = $em->getRepository('Xxxxx\XxxxxBundle\Entity\Colour')->findBy(array('name'=>'red'); 
$products = $em->getRepository('Xxxxx\XxxxxBundle\Entity\Product')->findBy(array('colours'=>$colours)); 

这是我的YAML配置:

Xxxxx\XxxxxBundle\Entity\Product: 
    type: entity 
    manyToMany: 
    colours: 
     targetEntity: Colour 
     joinTable: 
     name: Product_Colour 
     joinColumns: 
      product_id: 
      referencedColumnName: id 
     inverseJoinColumns: 
      colour_id: 
      referencedColumnName: id 

Xxxxx\XxxxxBundle\Entity\Colour: 
    type: entity 
    id: 
    id: 
     type: integer 
     generator: 
     strategy: AUTO 
    fields: 
    hex: 
     type: string 
     length: 320 
    name: 
     type: string 
     length: 320 

我得到的错误信息是:

Notice: Undefined index: joinColumns in /home/xxx/public_html/products/vendor/doctrine/lib/Doctrine/ORM/Persisters/BasicEntityPersister.php line 1217 

会有人能照到这是为什么不工作的一些情况。

回答

8

我知道这是一个老问题,但如果其他人通过谷歌来到这里(像我一样),我不得不避开了findBy和存储库中的使用DQL:

$products = $em->getRepository('Vendor\Bundle\Entity\Product')->findByColours($colours); 

,在库:

public function findByColours($colours) 
{ 
    $qb = $this->getEntityManager()->createQueryBuilder(); 
    $qb ->select(array('p')) 
     ->from('VendorBundle:Product', 'p') 
     ->join('p.colours', 'c', 'WITH', $qb->expr()->in('c.id', $colours)); 
    $result = $qb->getQuery()->execute(); 
    return $result; 

} 

您可能需要根据$颜色改变连接。这假定它是一个颜色ID数组。如果它是一个字符串,你可以放弃in(),或者如果它是一个字符串数组,你需要绑定字符串作为参数(参见下面的链接)。澄清expr()等是在Doctrine docs

我不知道为什么Undefined index: joinColumns发生,但这是一个方法,完全侧面它。希望有人能澄清这个错误,因为我的解决方案为多对多关系增加了额外的工作。