问题
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