我在 Symfony 2.8 应用程序中使用学说查询构建器获取结果时遇到一些麻烦:
我这里有 3 个实体:
- 歌曲
- 艺术家
- 类别
所有歌曲至少有 1 位艺术家和 1 个类别
歌曲与艺术家有manytomany关系,也与类别有manytomany关系
我想获取与赋予此函数的一首歌曲具有相同艺术家或类别的歌曲实体:
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 查询,将 ids 设置为参数,例如 something_id in (1,2)
,效果很好...
编辑
现在我知道只有艺术家 x 的歌曲 A 会匹配一些只有艺术家 x 的歌曲;对于类别也是如此。可能是类型问题(字符串 VS int)导致 in(x,y)
而不是 in (x)
出现问题?...
最佳答案
据我所知,Doctrine 使用 DQL(Doctrine 查询语言),而不是 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
关于php - Doctrine 查询生成器未给出所有结果 : many-to-many searching id in (x, y),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45195905/