教义实体发现很多人

时间:2011-09-19 00:14:36

标签: symfony1 doctrine-orm

我在产品和颜色之间存在多种关系。

我想做的是按颜色找到产品。

例如)

$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

有人能够阐明为什么这不起作用。

1 个答案:

答案 0 :(得分:9)

我知道这是一个老问题,但如果有其他人通过Google到达这里(就像我一样),我必须避开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;

}

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

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