I am trying to reproduce the following query using the QueryBuilder so I can use the paginator:
SELECT *, ( 3959 * acos( cos( radians($latitude) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians($longitude) ) + sin( radians($latitude) ) * sin( radians( latitude ) ) ) ) AS distance FROM table HAVING distance < $radius ORDER BY distance;
This is my attempt:
$builder = $this->modelsManager->createBuilder()
->columns(['*', 'distance' => '(6371 * acos(cos(radians(' . $lat . ')) * cos(radians(lat)) * cos(radians(lon) - radians(' . $lon . ')) + sin(radians(' . $lat . ')) * sin(radians(lat))))'])
->from('Multiple\Backend\Models\Posts')
->having('distance < ' . (int) $radius)
->where('module_id = ' . (int) $moduleId)
->orderBy('id DESC');
This is the error it produces:
Fatal error: Uncaught exception 'Phalcon\Mvc\Model\Exception' with message 'Column 'distance' doesn't belong to any of the selected models (1), when preparing: SELECT COUNT(*) [rowcount] FROM [Multiple\Backend\Models\Posts] WHERE module_id = 21 HAVING distance < 100' in /Applications/MAMP/htdocs/click_v2/apps/webservice/controllers/PostsController.php on line 78
If I comment the line ->having('distance < ' . (int) $radius)
then it works fine and calculates the correct distance but does not filter the results.
How do I use the distance alias in that having or where clause?