【问题标题】:Create subquery using query builder使用查询生成器创建子查询
【发布时间】:2017-01-17 09:08:01
【问题描述】:

我尝试在 Doctrine 查询生成器中转换 SQL 查询(效果很好),但我没有成功,因为它包含一个子查询

这是我的 SQL 查询:

SELECT * 
FROM `navigation` 
WHERE `parent_id` = 
(
     SELECT `id` 
     FROM `navigation` 
     WHERE `parent_id` = 47 
     AND `nav_type`= 'nav'
     AND `published` = 1 
     AND `title` = 'Top'
)

这就是我在我的存储库中尝试过的:

class NavigationRepository extends EntityRepository
{
    public function test($parentId, $type, $status, $title)
    {
        $subQuery = $this->createQueryBuilder('n2')
            ->select('n2.id')
            ->where('n2.parent = :parent')
            ->andWhere('n2.type = :type')
            ->andWhere('n2.status = :status')
            ->andWhere('n2.title = :title')
            ->setParameter('parent', $parentId)
            ->setParameter('type', $type)
            ->setParameter('status', $status)
            ->setParameter('title', $title)
            ->getDQL();

        $qb = $this->createQueryBuilder('n');
        $qb
            ->where(
                $qb->expr()->eq('n.parent', '('.$subQuery.')')
            )
            ->getQuery()
            ->getResult();

        return $qb
            ->getQuery()
            ->getResult();
    }
}

但是我收到了这个错误:

QueryException: Invalid parameter number: 绑定变量的数量 令牌数不匹配

为什么?看来我还有正确数量的参数...

【问题讨论】:

    标签: php sql symfony doctrine-orm subquery


    【解决方案1】:

    您应该在$qb 上调用setParameter() 而不是$subQuery。 DQL 不包含插值参数,它只是一个常规字符串。

    【讨论】:

    • 我不知道您的查询是做什么的或您的数据库是什么样的。您询问的参数数量不正确。
    • 是的,谢谢,我用您的解决方案更新了我的答案,并输入了我如何调用我的查询
    • 尝试使用 ->getQuery()->getSql() 转储 SQL 查询并手动检查它生成的内容
    猜你喜欢
    • 2021-02-20
    • 2020-11-24
    • 2018-07-03
    • 2015-07-10
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多