【问题标题】:KnpPaginatorBundle - default order byKnpPaginatorBundle - 默认顺序
【发布时间】:2020-03-27 06:45:10
【问题描述】:

我正在尝试让 KnpPaginatorBundle 在查询完成后默认“排序依据”。

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

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

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

有什么想法吗?

【问题讨论】:

    标签: symfony knppaginator knppaginatorbundle


    【解决方案1】:

    我相信 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];
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-04-13
      • 1970-01-01
      • 1970-01-01
      • 2011-05-07
      • 2011-12-01
      • 2021-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多