php - Doctrine 查询生成器未给出所有结果 : many-to-many searching id in (x, y)

标签 php mysql symfony doctrine-orm many-to-many

我在 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/

相关文章:

php - Laravel:使用 Linode 的存储对象作为 AWS S3 的替代方案

php - 处理内存限制

mysql - 将 MySQL 子查询重写为 join

php - 在哪里构建使用类型提示属性反序列化嵌套对象的方法?

symfony - 登录后从登录页面重定向FOSUserBundle

php - 或者在带有子查询的 Laravel 查询生成器中的 WHERE IN

php - 从绝对路径向上 move 文件夹

php - 降低浏览器速度的 jQuery Loop

mysql - 安排定期 mysql 脚本每小时自动运行

php - 无法访问字符串变量的属性