2015-04-20 74 views
2

我目前正在試圖用Doctrine2 QueryBuilder建立一個查詢。但是,我試圖執行以下操作時被卡住:如何使用QueryBuilder構建查詢?

我有一個名爲'Customer'的實體。該實體與「用戶」具有多對多關係。 '用戶'再次站在與PhoneNumber的ManyToMany-Relation中。

所以這幾乎是:

Customer <- @ManyToMany -> User <- @ManyToMany -> PhoneNumber 

現在我想選擇一個基於******中國客戶。所以現在我有以下幾點:現在

$qb = $this->getEntityManager()->createQueryBuilder(); 
$qb 
    ->select('c') 
    ->from('AppBundle:Customer', 'c') 
    ->join('AppBundle:User', 'u') 
    ->join('AppBundle:PhoneNumber', 'u'); 

問題是,我不知道如何構建查詢的WHERE截面。原因是可能有幾個用戶和幾個綁定到客戶的電話號碼。你有關於如何繼續的想法嗎?

+3

這兩個m:n關係看起來都不錯。一個電話號碼可以屬於多個用戶?一個用戶可以是多個客戶,反之亦然? – marekful

+0

你爲'User'&'PhoneNumber'設置了相同的別名,就像@MarcellFulop所說的那樣,你有無效的關係,多用戶可以有多少個相同的電話號碼? – ghanbari

+0

它有什麼問題?例如,如果有兩個兄弟註冊後仍然與父母住在一起 - 那麼電話號碼顯然是相同的。我注意到了別名問題並修復了它,但我仍然遇到同樣的問題。 – chrisp

回答

0

如果你有實體的mappedBy/InversedBy你可以做

$qb = $this->getEntityManager()->createQueryBuilder(); 
$qb 
    ->select('c') 
    ->from('AppBundle:Customer', 'c') 
    ->innerJoin('c.users', 'u') 
    ->innerJoin('u.phoneNumbers', 'p') 
    ->andWhere('p.number = :numberPhone') 
    ->setParameter('numberPhone', $varPhoneNumber) 
; 
0

我的解決辦法:

使用innerJoin()和 '成員' 解決了這一問題。這樣我可以將每個實體與任何其他實體連接起來。例如:

$qb = $this->getEntitiyManager()->createQueryBuilder() 
    ->select('c') 
    ->from('AppBundle:Customer', 'c') 
    ->innerJoin('AppBundle:User', 'u', 'WITH', 'c.id MEMBER OF c.users') 
    ->innerJoin('AppBundle:PhoneNumber', 'ph', 'WITH', 'ph.id MEMBER OF u.phoneNumbers') 
    ->orWhere($qb->expr()->orX(
      $qb->expr()->eq('ph.number', ':number') 
    )) 
    ->setParameter('number', $somePhoneNumber);