Haversine distance calculation between two points in Laravel

前端 未结 7 1539
迷失自我
迷失自我 2020-12-13 16:45

I\'m working on a laravel appliciation in which I need to find all the products that are within a certain radius of the user\'s coordinates. Products have a one to many rela

相关标签:
7条回答
  • 2020-12-13 17:13

    I think what you need is the query builder to build a join. With a join you have the fields of both tables available in your query. Currently you are using relationships with eager loading, this will preload the related users, but they cannot be used inside the SQL (Laravel will actually execute 2 queries).

    Anyway I wouldn't try to calculate the haversine formula in one step with SQL, this cannot be really performant, and the query could become difficult to maintain in my opinion. This is what i would do instead:

    1. Calculate an envelope with minimum/maximum of latitude and longitude, it should be a bit bigger than your search radius.
    2. Make a fast query with a join of product and user, and just check whether the user location is inside this envelope.
    3. For each element of the resulting list calculate the exact haversine distance with PHP (not SQL), delete rows which are outside the radius, and sort the list accordingly.
    0 讨论(0)
提交回复
热议问题