首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >KnpPaginatorBundle -默认排序依据

KnpPaginatorBundle -默认排序依据
EN

Stack Overflow用户
提问于 2019-12-03 00:00:34
回答 1查看 243关注 0票数 0

我正在尝试让KnpPaginatorBundle在查询完成后默认设置"order by“。

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

代码语言:javascript
复制
[
    'defaultSortFieldName'      => 'i.name',
    'defaultSortDirection'      => 'desc'
]

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

有什么想法吗?

EN

回答 1

Stack Overflow用户

发布于 2019-12-04 18:06:19

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

一个最小的例子:

代码语言:javascript
复制
<?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];
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59142569

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档