查询生成器在多对多关系上联接

2022-08-30 18:20:46

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

但是,我无法构建正确的查询生成器句子,因为我不知道如何引用 from my,因为我的类别 ID 中没有字段。superCategorycategorysuperCategory

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

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);

答案 1

明白了:

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

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


答案 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();

推荐