Symfony 3 参数太多

Symfony 3 Too many parameters

我是 Symfony 的新手,运行查询时出现错误:

public function getFilteredArticles($page, $nbPerPage, $data) {
        $query = $this->createQueryBuilder('a')
                ->leftJoin('a.images', 'i')
                ->addSelect('i')
                ->leftJoin('a.type_stockage', 't')
                ->addSelect('t')
                ->leftJoin('a.famille', 'f')
                ->addSelect('f');
        if ($data['famille'] != '') {
            $query->where('f.id = :famille')
                    ->setParameter('famille', $data['famille']);
        }
        if ($data['rds'] == false) {
            $query->where('a.stock_actuel > 0');
        }
        if ($data['recherche'] != '' && $data['recherche'] != null) {
            $query->where('a.ref_article LIKE :recherche')
                    ->setParameter('recherche', '%' . $data['recherche'] . '%');
        }
        $query->leftJoin('a.sousfamille', 's')
                ->orderBy('a.ref_article', 'ASC')
                ->getQuery();

        $query->setFirstResult(($page - 1) * $nbPerPage)
                ->setMaxResults($nbPerPage);

        return new Paginator($query, true);
    }

如您所见,此查询具有条件参数,即 returns 我需要 table 的文章列表。但是当我 运行 这个查询来填充我的 table 时,我得到了错误:

An exception has been thrown during the rendering of a template ("Too many parameters: the query defines 0 parameters and you bound 1").

我不知道他为什么期望 0 个参数。我尝试改用 setParameters,但结果是一样的。

有人有想法吗?

您应该使用 andWhere() 方法而不是 where()
where() 方法会删除所有以前的位置,但 setParameter() 不会。这就是为什么他找到了比 where 子句更多的参数。

如果条件没有意义作为第一个条件,我个人从不使用where,以避免此类错误。

    if ($data['famille'] != '') {
        $query->andWhere('f.id = :famille')
                ->setParameter('famille', $data['famille']);
    }
    if ($data['rds'] == false) {
        $query->andWhere('a.stock_actuel > 0');
    }
    if ($data['recherche'] != '' && $data['recherche'] != null) {
        $query->andWhere('a.ref_article LIKE :recherche')
                ->setParameter('recherche', '%' . $data['recherche'] . '%');
    }

where() php 文档

Specifies one or more restrictions to the query result.
Replaces any previously specified restrictions, if any.

andWhere() php 文档

Adds one or more restrictions to the query results, forming a logical conjunction with any previously specified restrictions.

我在 Symfony 4 中使用 Doctrine 2.6 的错误是 Too many parameters: the query defines 0 parameters and you bound 2

问题是我没有将 andWhere 方法中的参数定义为

$this->createQueryBuilder('q')
...
->andWhere('q.propertyDate IS NOT NULL') //this also couldn't find anywhere
->andWhere('q.parameterName = :parameterName')
->setParameters(['q.parameterName' => $parameterName, ...2nd parameter])

由于我找不到任何问题的答案,但与这个问题类似,我想也许可以帮助像我一样挣扎的人。

同样在 symfony 5 和 6 中,您应该使用 andWhere() 方法而不是 where()。 where() 方法会删除所有以前的位置,但 setParameter() 不会。这就是为什么他找到了比 where 子句更多的参数。