首页 > 解决方案 > 如何在 cakephp 3.x 路由中包含分页参数

问题描述

我希望我的订单索引在我打开起始页时按 id 降序排序/。以下是我到目前为止尝试过的路线:

$routes->connect('/', ['controller' => 'Orders', 'action' => 'index', 'sort' => 'id', 'direction' => 'desc']);

$routes->connect('/', ['controller' => 'Orders', 'action' => 'index', '?' => ['sort' => 'id', 'direction' => 'desc']]);

$routes->connect('/', ['controller' => 'Orders', 'action' => 'index', 'pass' => ['sort' => 'id', 'direction' => 'desc']]);

它们都不起作用(即忽略排序参数),即使当我将第二个选项与?.

我该如何设置路线?

编辑:

/?sort=id&direction=desc

这个 url 显示我想在/.

标签: cakephpcakephp-3.0

解决方案


您可以使用RedirectRoute将发出 HTTP 301 重定向的 a:

$routes->connect('/', ['controller' => 'Orders', 'action' => 'index', '?' => ['sort' => 'id', 'direction' => 'desc']], ['routeClass' => 'RedirectRoute']);

或者,您可以在控制器中设置分页参数并在那里添加排序。请注意,即使您单击另一列进行排序,此排序仍将保持不变,并且生成的 SQL 将具有以下内容:ORDER BY Orders.created ASC, Orders.id DESC.

如果不需要这种行为,您可以通过在存在sortdirection查询参数时不设置默认排序来避免这种情况。

像这样的东西:

class OrdersController extends AppController
{

    /**
     * Index method
     *
     * @return \Cake\Http\Response|void
     */
    public function index()
    {
        $query = $this->getRequest()->getQueryParams();

        if (empty($query['sort']) || empty($query['direction'])) {
            $this->paginate['order'] = ['Orders.id' => 'desc'];
        }

        $orders = $this->paginate($this->Orders);

        $this->set(compact('orders'));
    }
}

推荐阅读