cakephp - 如何在 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 显示我想在/
.
解决方案
您可以使用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
.
如果不需要这种行为,您可以通过在存在sort
和direction
查询参数时不设置默认排序来避免这种情况。
像这样的东西:
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'));
}
}
推荐阅读
- javascript - 如何在 AJAX 回调中转换我的图表数据创建
- c# - c# Asp.NET mvc view create element's database dynamic
- angular - 使用没有 formGroup 的表单数组
- python - 将不支持的 keras 层或模型导入 MATLAB
- scala - 在 Akka Streams 中使用 Keep.right / Keep.left 不会影响结果
- reactjs - 寻找具有移动 Web 焦点选项/功能的 ReactJS 条码扫描器
- javascript - 如何向函数添加方法或道具?
- python - 通过单选按钮和过程传递变量
- specflow - 如何存储在 Azure DevOps 中生成的历史 SpecFlow+ LivingDoc 报告
- powershell - 循环前按名称对文件进行排序