CackePHP 3 formatResults()按字段动态创建 [英] CackePHP 3 formatResults() ORDER by field created dynamically

查看:82
本文介绍了CackePHP 3 formatResults()按字段动态创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望对在 formatResults()

$users = $this->Users
->find('all')
->formatResults(function ($users) use ($lat, $lng) {
    return $users->map(function ($user) use ($lat, $lng) {
        $user->distance = getDist($lat, $lng);
        return $user;
    });
})
->order([
    'distance' => 'ASC'
]);

[...]

$this->set('users', $this->paginate($users));

字段 $ user->距离不在数据库中。
$ user->距离包含浮点数( getDist($ lat,$ lng);

The field $user->distance is not in the database. $user->distance contains a float (getDist($lat, $lng);) that is variable depending on the position of the user at the time of his request.

->order([
    'distance' => 'ASC'
]);

返回错误:未找到列:1054未知列'Users.distance 在'order子句'

我的问题是:当接收来自用户的信息时,我可以对我动态创建的字段进行排序吗? / p>

My question is this: Can I sort a field I have dynamically created when receiving information from the user?

推荐答案

您可以按php中计算出的字段进行排序,但不适用于分页,因为进行排序需要全部数据库中的记录。您需要创建一个在SQL中运行的等效逻辑,以便进行排序。

You can sort by a field calculated in php, but it will not work for pagination, since for doing the sorting you need all the records from the database. You need to create an equivalent logic that runs in SQL so you can sort.

选中此插件可以帮助您计算距离并按距离进行排序 https://github.com/dereuromark/cakephp-geo/

Check this plugin that can help you calculate the distances and sort by them https://github.com/dereuromark/cakephp-geo/

这是 find('distance')自定义查找器,您可以在使用提供的行为时将其动态添加到表中。 https://github.com/dereuromark /cakephp-geo/blob/master/src/Model/Behavior/GeocoderBehavior.php#L223

The is the find('distance') custom finder that you can dynamically add to your table when using the provided behavior. https://github.com/dereuromark/cakephp-geo/blob/master/src/Model/Behavior/GeocoderBehavior.php#L223

这篇关于CackePHP 3 formatResults()按字段动态创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆