当我使用大于、小于或等于过滤器时,出现 count() 错误

问题描述 投票:0回答:1

在书籍页面上,我添加了按书籍作者数量的过滤器,我可以在其中指定 (=n | >n |

public function findPaginated(InterpretationTranslationSourceFilter $filter): NewPaginator
{
    $qb = $this->createQueryBuilder('s')
        ->leftJoin('s.authorToSourceRelations', 'atsr')
        ->select('s as interpretationTranslationSource')
        ->addSelect('COUNT(DISTINCT atsr.id) AS authorToSourceRelationsCount')
        ->groupBy('s.id');

    if ($filter->isHasLink() OR $filter->getDontHasLink()) {
        if ($filter->isHasLink()) {
            $qb->andWhere('s.url IS NOT NULL');
        }

        if ($filter->getDontHasLink()) {
            $qb->andWhere('s.url IS NULL');
        }
    }

    if ($filter->getSortByAuthorsCount()) {
        $comparisonOperator = substr($filter->getSortByAuthorsCount(), 0, 1);
        $authorsCount = (int) substr($filter->getSortByAuthorsCount(), 1);

        switch ($comparisonOperator) {
            case '=':
                $qb->having('authorToSourceRelationsCount = :authorsCount')
                    ->setParameter('authorsCount', $authorsCount);
                break;
            case '>':
                $qb->having('authorToSourceRelationsCount > :authorsCount')
                    ->setParameter('authorsCount', $authorsCount);
                break;
            case '<':
                $qb->having('authorToSourceRelationsCount < :authorsCount')
                    ->setParameter('authorsCount', $authorsCount);
                break;
            default:
                $qb->orderBy('s.title', 'ASC');
                break;
        }
    }

    if ($filter->getTitle()) {
        $qb->andWhere('s.title like :title')
            ->setParameter('title', '%' . $filter->getTitle() . '%');
    }

    if ($filter->getUrl()) {
        $qb->andWhere('s.url LIKE :url')
            ->setParameter('url', '%' . $filter->getUrl() . '%');
    }

    return new NewPaginator($qb, $filter);
}

当我指定任何值时,我收到错误:
count():参数#1($value)必须是 Countable|array 类型,Doctrine\ORM\Query\Expr\Andx 给定

我试图补充我的查询,重建它们,但一切都是徒劳的

symfony doctrine-orm doctrine symfony-forms
1个回答
0
投票

直接在条件中将

HAVING
子句更改为
COUNT(DISTINCT atsr.id)
。这应该可以解决问题。 HAVING 子句应该对聚合函数的结果进行操作,在本例中,它是不同作者 ID 的计数。

switch ($comparisonOperator) {
            case '=':
                $qb->having('COUNT(DISTINCT atsr.id) = :authorsCount')
                    ->setParameter('authorsCount', $authorsCount);
                break;
            case '>':
                $qb->having('COUNT(DISTINCT atsr.id) > :authorsCount')
                    ->setParameter('authorsCount', $authorsCount);
                break;
            case '<':
                $qb->having('COUNT(DISTINCT atsr.id) < :authorsCount')
                    ->setParameter('authorsCount', $authorsCount);
                break;
            default:
                $qb->orderBy('s.title', 'ASC');
                break;
}

如果仍有问题,请尝试将

having
替换为
andHaving

© www.soinside.com 2019 - 2024. All rights reserved.