【问题标题】:Query builder join on ManyToMany relationship查询构建器加入多对多关系
【发布时间】:2012-04-19 18:46:11
【问题描述】:

我正在尝试使用查询生成器来选择属于某个 superCategory 的所有类别(categorysuperCategory 具有多对多关系)。

但是,我无法构建正确的查询构建器语句,因为我不知道如何从我的 category 引用 superCategory,因为我的类别 ID 中没有 superCategory 字段。

数据库中的对象如下所示:

Category:
  id
  name

SuperCategory
  id
  name

categories_superCategories
  id
  category_id
  superCategory_id

这是我的对象(yml 文件)的定义:

YOP\YourOwnPoetBundle\Entity\TraitCategory:
  type: entity
  repositoryClass: YOP\YourOwnPoetBundle\Repository\TraitCategoryRepository
  table: null
  fields:
    id:
      type: integer
      id: true
      generator:
        strategy: AUTO
    name:
      type: string
      length: '255'
  lifecycleCallbacks: {  }
  manyToMany:
    superCategories:
      targetEntity: SuperCategory
      joinTable:
        name: traitCategories_superCategories
        joinColumns:
          traitCategory_id:
            referencedColumnName: id
        inverseJoinColumns:
          superCategory_id:
            referencedColumnName: id

YOP\YourOwnPoetBundle\Entity\SuperCategory:
  type: entity
  repositoryClass: YOP\YourOwnPoetBundle\Repository\SuperCategoryRepository
  table: null
  fields:
    id:
      type: integer
      id: true
      generator:
        strategy: AUTO
    name:
      type: string
      length: '255'
  lifecycleCallbacks: {  }
  manyToMany:
    msgCategories:
      targetEntity: MsgCategory
      mappedBy: superCategories
    traitCategories:
      targetEntity: TraitCategory
      mappedBy: superCategories

我将如何构建查询构建器语句来获取属于某个 superCategory 的类别?

我的CategoryRepository里面的查询:

$this->createQueryBuilder('c')
            ->innerJoin( ?????? )
            ->setParameter('superCategoryName', $superCategoryName);

【问题讨论】:

    标签: php symfony doctrine-orm


    【解决方案1】:

    知道了:

    public function findBySuperCategoryName($superCategoryName)
    {
        return $this->createQueryBuilder('c')
                ->innerJoin('c.superCategories', 's', 'WITH', 's.name = :superCategoryName')
                ->setParameter('superCategoryName', $superCategoryName);
    }
    

    问题是我必须要求 c.superCategories 而不是 c.superCategory !

    【讨论】:

    • 在 2020 年仍然是一个有效的答案!谢谢。
    • 2021 年仍然是一个有效的答案!谢谢。
    【解决方案2】:

    类似:

    $this->createQueryBuilder()
            ->select('s')
            ->from('SuperCategory', 's')
            ->innerJoin('s.Category c ON c.category_id = s.superCategory_id')
            ->where('s.name = :superCategoryName')
            ->setParameter('superCategoryName', $superCategoryName)
            ->getQuery()
            ->getResult();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-02
      • 2015-07-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多