dskm94301 2019-05-28 17:53
浏览 60

如何使用post计算字段对Cakephp查询进行排序并将其传递给paginate?

Have a formatResults callback function that adds a "custom calculated" field into the entities post returned from a model query in my Cakephp. I would like to sort by this field and use this on a paginate is this possible?

So far i cannot accomplish this because the paginate limits the records fetched and therefore only records less than the paginator limit get sorted and not all the resultset...

Current code:

    $owners = $this->Owners->find('all');

    $owners->formatResults(function (\Cake\Collection\CollectionInterface $owners) {

        $owners = $owners->map(function ($entity) {

            $entity->random = rand(0,1);

            return $entity;

        });

        return $owners->sortBy(function ($item){

            return $item->random;

        },SORT_DESC);

    });

This works as expected:

$owners->toArray();

This does not:

$owners = $this->paginate($owners);
$owners->toArray();

Mainly because its "callback processing" only the first 10 records, i would like to process the whole resultset.

  • 写回答

1条回答 默认 最新

  • douluan1533 2019-05-29 10:38
    关注

    After diggin around ive found a similar topic opened by a previous user on the this link, it seems that is not possible to use pagination sort in other than the fields in the database.

    As a result, i would suggest:

    1 - Either alter your model logic, to accommodate your requirements by creating virtual fields or alter database schema to include this data.

    2 - If the data requires further or live processing and it cannot be added or calculated in the database, perhaps programming a component that will replicate the paginate functionality on a cakephp collection would be a good option.The downside of this approach is that all records will be returned from the database which may present performance issues on large resultsets.

    评论

报告相同问题?

悬赏问题

  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)