J
J
jarvis2018-02-14 08:51:26
MySQL
jarvis, 2018-02-14 08:51:26

How to correctly formulate a many-to-many query with geolocation to the database through the Laravel framework?

Hello, there was a problem with the correct formation of queries to the database
In short, we have a "Scripts" model that contains several id of the "Points" model. One point can belong to many scenarios.
The "Points" model contains fields such as "longitude" and "latitude"
I need to get all scenarios that are near a certain geopoint. How to correctly formulate a query or transform the original one? I don’t want to manually loop through all the points and get scripts for them in the code itself.
now the points are obtained as follows:

$radius = 100;
$max_distance = 20;
$lat = {your_lat};
$lng = {your_lng};

 return $points = DB::select(
               'SELECT * FROM
                    (SELECT id, name, address, phone, latitude, longitude, (' . $radius . ' * acos(cos(radians(' . $lat . ')) * cos(radians(latitude)) *
                    cos(radians(longitude) - radians(' . $lng . ')) +
                    sin(radians(' . $lat . ')) * sin(radians(latitude))))
                    AS distance
                    FROM points) AS distances
                WHERE distance < ' . $max_distance . '
                ORDER BY distance
                OFFSET 0
                LIMIT 20;
            ');

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question