CackePHP 3 formatResults() ORDER by field created dynamically

痞子三分冷 提交于 2019-12-04 06:04:10

问题


I wish to sort on a field that I dynamically creates in 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));

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'
]);

return an error : Column not found: 1054 Unknown column 'Users.distance' in 'order clause'

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


回答1:


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.

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

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



来源:https://stackoverflow.com/questions/30974456/cackephp-3-formatresults-order-by-field-created-dynamically

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!