Question

For context, though the scope is not limited to this, I'm using CakePHP 2.4.4 with it's pagination function. This queries for results (with ORDER, LIMIT and OFFSET, I believe), and once the results are returned, I calculate a field. In this case, the user enters a Postcode, and upon results being returned, the geographical distance between the search postcode and the result postcodes are individually calculated. I can't order by this, as I only have one page of results at a time.

How would I do this manually? I imagine I could get all results in a query, then calc distance for each result, then order, then drop those not on that page, but that seems very expensive. Autotrader, for example, return hundreds of thousands of results, and they can be ordered by distance, calculated there and then.

The maths is done in PHP on my project, but I expect this needs to be moved to within a query, but I think that makes it expensive.

How can I order all results by a calculated field not actually stored in the database?

Was it helpful?

Solution

Not sure PHP here is the right place to do the math. Especially if there is a lot of records to filter in that table.

You might want to look at http://www.dereuromark.de/2012/06/12/geocoding-with-cakephp/

You seem to be working with distances. In that article the whole calculation is done in the SQL directly - using virtual fields and a clean approach via behavior. Try to get this working. It will make it not only easy for you to work with distances or lat/lng fields, it will also keep it DRY.

Sorting and filtering is all included.

OTHER TIPS

If you are doing complex calculation move the code to a store procedure.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top