【问题标题】:How to paginate an array query result in cakephp 3如何在 cakephp 3 中对数组查询结果进行分页
【发布时间】:2021-01-30 13:26:24
【问题描述】:
  1. 您好,我有一组要分页的查询结果。但不知何故,我收到一条错误消息:

找不到与分页兼容的对象。

这是我当前的代码:

        $this->paginate = ['limit' => 10];

        $comment = TableRegistry::get('Comments');
        $comments = $comment
            ->find()
            ->where(['Comments.post_id' => $id])
            ->contain(['Users'])
            ->order(['Comments.created' => 'ASC'])
            ->all()
            ->toArray(); //the results will be array

        $comments = $this->paginate($comments);
  1. 我的第二个问题是,有没有办法在控制器中进行查询时始终使用数组结果而不是对象结果,这样我就不需要将 ->toArray() 包含到我的代码中?

谢谢!

【问题讨论】:

    标签: cakephp pagination cakephp3


    【解决方案1】:

    内置分页器不支持数组,它只适用于查询。如果需要对数组进行分页,则必须构建自定义分页器。

    但是一开始不需要传递数组,而是传递查询,如果确实需要,将分页器返回的结果集(\Cake\ORM\ResultSet|\Cake\Datasource\ResultSetInterface)转换为数组,结果是一样的,即:

    $comments = $comment
        ->find()
        ->where(['Comments.post_id' => $id])
        ->contain(['Users'])
        ->order(['Comments.created' => 'ASC']);
    
    $comments = $this->paginate($comments);
    $comments = $comments->toArray();
    

    我不确定你为什么要这样做,因为结果集实现了\ArrayAccess,即它可以像数组一样被迭代和访问,你只是通过这种转换来限制自己。

    此外,没有真正直接的方法可以自动执行此操作,唯一接近的方法是使用模型的 beforeFind() event/callback 修改查询,并附加一个 result formatter 将结果集转换为数组,但结果格式化程序预计会返回\Cake\Collection\CollectionInterface,因为他们在某种程度上承诺也会收到它。格式化程序是按顺序处理的,后续的格式化程序会收到前一个格式化程序返回的值。

    【讨论】:

      猜你喜欢
      • 2019-09-07
      • 2023-03-10
      • 2017-09-15
      • 2015-08-20
      • 2020-01-11
      • 1970-01-01
      • 2019-12-23
      • 2011-03-24
      • 2015-04-05
      相关资源
      最近更新 更多