I've been working on calculation distances between two pairs of coordinates. The issue arises when you are working with a relation.
For example, I have a user table and an addresses table. Addresses table as a column user_id
so each user has multiple addresses.
UPDATE
The latitude and the logitude are stored on a relation table called addresses and not on the users table.
Someones already come across this issue a few years ago, but it was never responded to. https://laracasts.com/discuss/channels/eloquent/haversine-query-using-eloquent
When calculation the distance, this is what i have so far.
$haversine = "(6371 * acos(cos(radians(cast(" . $coordinates->latitude . "as numeric)))
* cos(radians(latitude))
* cos(radians(longitude)
- radians(cast(" . $coordinates->longitude . " as numeric)))
+ sin(radians(cast(" . $coordinates->latitude . " as numeric)))
* sin(radians(latitude))))";
$users = $users->whereHas('addresses', function ($q) use ($radius, $haversine) {
$q->selectRaw("{$haversine} AS distance")
->whereRaw("distance < ?", [$radius]);
})->get();
But this throws an error
Undefined function: 7 ERROR: operator does not exist: bigint = character varying LINE 6: ...) AS distance from "addresses" where "users"."id" = "address... ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. (
Ive tried playing around with the formula, and realized the the issue lies within the relation. Just cant put my finger on it. Has anyone come across this issue?
Thank you