2012-04-06 2 views
12

Я пытаюсь использовать построитель запросов, чтобы выбрать все категории, принадлежащие определенной суперкатегории (категория и суперкатегория имеют отношение много-много). Однако я не могу построить правильное предложение построения запроса, потому что я не знаю, как ссылаться на суперкатегорию из моей категории, поскольку в моем идентификаторе категории нет поля superCategory.Query builder присоединяется ко многим отношениям

объекты в базе данных выглядит следующим образом:

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 

Как бы построить предложение построителя запроса, чтобы получить категории, принадлежащие определенной суперкатегории?

Запрос внутри моего CategoryRepository:

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

Спасибо ...

ответ

27

Понял:

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(); 
Смежные вопросы