0
  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() 包含到我的代码中?

谢谢!

4

1 回答 1

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()事件/回调来修改查询,并附加一个将结果集转换为数组的结果格式化程序,但结果格式化程序有点预期返回\Cake\Collection\CollectionInterface,因为他们在某种程度上承诺也会收到。格式化程序是按顺序处理的,后续的格式化程序会收到前一个格式化程序返回的值。

于 2020-10-16T11:29:53.143 回答