【问题标题】:Doctrine Entity findBy Many to Many教义实体 findBy 多对多
【发布时间】:2011-09-19 00:14:36
【问题描述】:

我在产品和颜色之间有多对多的关系。

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

例如)

$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

有人能解释一下为什么这不起作用吗?

【问题讨论】:

    标签: symfony1 doctrine-orm


    【解决方案1】:

    我知道这是一个老问题,但如果其他人通过 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,但这是一种完全避开它的方法。希望有人能澄清错误,因为我的解决方案为多对多关系增加了额外的工作。

    【讨论】:

      猜你喜欢
      • 2014-08-15
      • 1970-01-01
      • 1970-01-01
      • 2019-06-23
      • 1970-01-01
      • 2021-11-14
      • 2012-12-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多