2017-07-19 39 views
0

我面對一些麻煩讓我的教義查詢生成器的結果,在Symfony的2.8應用程序:主義查詢生成器並沒有給所有的結果:很多一對多的(X,Y)搜索ID

我這裏有3個實體:

  • 藝術家
  • 類別

所有的兒子GS至少有1藝術家和1個類別

多對多關係與藝術家,並多對多類別藏漢

我想獲得具有樂曲實體相同的藝術家或類別作爲一首歌賦予此功能:

public function findRelatedSongs($song) 
{ 
    $em = $this->getEntityManager(); 

    $artistsIds = $this->getArtistsIds($song); 
    //returns a string like '1,2,3' 
    $categoriesIds = $this->getCategoriesIds($song); 
    //returns a string like '1,2,3' 

    $q = $em->getRepository("BeatAdvisorBundle\Entity\Song") 
      ->createQueryBuilder('s') 
      ->join('s.artists', 'a') 
      ->join('s.categories', 'c') 
      ->where('a.id in (:artistsIds)') 
      ->orWhere('c.id in (:categoriesIds)') 
      ->andWhere('s.id <> :songId') 
      ->setParameter('artistsIds', $artistsIds) 
      ->setParameter('categoriesIds', $categoriesIds) 
      ->setParameter('songId', $song->getId()) 
      ->getQuery(); 

    $sql = $q->getSql(); 
    // here I can read the sql query generated 

    $result = $q->setMaxResults(16) 
       ->getResult(); 

    return $result; 
} 

它讓我回到相同的藝術家的相關歌曲,但不是在類別上。

我寫這個的方式有問題嗎?

如果我複製並粘貼SQL查詢,設置ID作爲參數,如something_id in (1,2)它的工作好...

編輯

現在我知道這首歌-A只有藝術家-X將匹配一些只有artist-x的歌曲;類別相同。可能是類型(字符串VS int)的問題導致in(x,y)而不是in (x)的問題?...

回答

0

據我所知,Doctrine使用DQL(Doctrine Query Language),而不是SQL。表達式有時會有點不同。您可以使用QueryBuilders Expression對象以編程方式構建您的表達式。

$qb->where(
    $qb->expr()->in('a.id', ':artistsIds'), 
    $qb->expr()->eq('s.id', ':songId') 
); 

參考: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/query-builder.html

+0

要去嘗試這個.. TY –

+0

同樣的結果......有可能是別的地方... –

0

OK,我的錯誤是我的設置參數字符串(IDS崩盤的陣列)。

我不得不放棄整數本身的陣列...