0

我试图让 KnpPaginatorBundle 在查询完成后默认“order by”。

我尝试了以下方法,但没有成功!

[
    'defaultSortFieldName'      => 'i.name',
    'defaultSortDirection'      => 'desc'
]

这样做的原因是因为我的下一个可排序选项不需要按名称排序,因此不想在查询中包含 order by。

有任何想法吗?

4

1 回答 1

0

我相信 KnpPaginatorBundle 会改变并使用您的 $_GET 全局变量,这并不理想。我发现更好的选择是自己控制排序。

一个最小的例子:

<?php

namespace App\Repository;

use App\Entity\Blog;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Knp\Component\Pager\PaginatorInterface;
use Symfony\Bridge\Doctrine\RegistryInterface;
use Doctrine\ORM\Query\Expr;

/**
 * @method Blog|null find($id, $lockMode = null, $lockVersion = null)
 * @method Blog|null findOneBy(array $criteria, array $orderBy = null)
 * @method Blog[]    findAll()
 * @method Blog[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class BlogRepository extends ServiceEntityRepository
{
    private const LIMIT_BLOGS_PER_PAGE = 20;
    private $paginator;

    public function __construct(RegistryInterface $registry, PaginatorInterface $paginator)
    {
        $this->paginator = $paginator;
        parent::__construct($registry, Blog::class);
    }

    public function getPaginatedBlogs(int $page, array $params = [], bool $isPublished = true)
    {
        list($sortKey, $order) = $this->getSorting(@$params['sort']);

        $qb = $this->createQueryBuilder('blog')
            ->where('blog.is_published = :is_published')
            ->setParameter('is_published', $isPublished);

        // Sort by order as requested by user
        $qb->orderBy($sortKey, $order);

        return $this->paginator->paginate(
            $qb->getQuery(),
            $page,
            self::LIMIT_BLOGS_PER_PAGE,
            []
        );
    }

    private function getSorting($sort)
    {
        switch ($sort) {
            case 'updated':
                $sortKey = 'blog.updated';
                $order = 'DESC';
                break;

            case 'title':
                $sortKey = 'blog.title';
                $order = 'ASC';
                break;

            default:
                $sortKey = 'blog.created';
                $order = 'DESC';
                break;
        }

        return [$sortKey, $order];
    }
}
于 2019-12-04T10:06:19.373 回答