2012-04-06 38 views
12

Tôi đang cố gắng sử dụng trình tạo truy vấn để chọn tất cả các danh mục thuộc về một danh mục siêu dữ liệu nhất định (danh mục và danh mục siêu có mối quan hệ nhiều đến nhiều). Tuy nhiên, tôi không thể xây dựng câu đúng của người xây dựng truy vấn vì tôi không biết cách tham chiếu đến Danh mục siêu hạng từ danh mục của mình vì không có trường siêu danh mục trong ID danh mục của tôi.Trình tạo truy vấn tham gia vào nhiều mối quan hệ

Các đối tượng trong cơ sở dữ liệu như sau:

Category: 
    id 
    name 

SuperCategory 
    id 
    name 

categories_superCategories 
    id 
    category_id 
    superCategory_id 

Dưới đây là định nghĩa của đối tượng của tôi (file 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 

Làm thế nào tôi sẽ xây dựng câu hỏi của người xây dựng truy vấn để có được các danh mục thuộc về một danh sách siêu dữ liệu nhất định?

Truy vấn bên CategoryRepository tôi:

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

Cảm ơn bạn ...

Trả lời

27

Got it:

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

Vấn đề là Tôi đã có để yêu cầu c.superCategories và không phải c.superCategory!

2

Cái gì như:

$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(); 
Các vấn đề liên quan