我正在尝试使用查询构建器来选择属于某个superCategory的所有类别(category和superCategory具有多对多的关系)。 但是,我无法构建正确的查询构建器句子,因为我不知道如何引用我的类别中的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);
谢谢...
答案 0 :(得分:33)
知道了:
public function findBySuperCategoryName($superCategoryName)
{
return $this->createQueryBuilder('c')
->innerJoin('c.superCategories', 's', 'WITH', 's.name = :superCategoryName')
->setParameter('superCategoryName', $superCategoryName);
}
问题是我不得不要求c.superCategories而不是c.superCategory!
答案 1 :(得分: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();