我正在尝试构建一个自定义查询(我正在使用Laravel 5.2但不知道如何使用Eloquent来构建我需要的查询),它计算距离并包含一个数据透视表来返回结果。我的查询工作没有数据透视表,但当我尝试用JOIN包含它时,它开始抛出一个错误。
这是我看到的错误:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE category_special.category_id = 107 HAVING distance < 22' at line 1
这是我现在遇到的抛出上述错误的查询:
SELECT
vendors.id AS vendor_id,
vendors.name AS vendor_name,
vendors.address,
vendors.city,
vendors.state,
vendors.zip,
vendors.latitude,
vendors.longitude,
(
3959 * acos (
cos ( radians(33.7835943) )
* cos( radians( latitude ) )
* cos( radians( longitude ) - radians(-111.95311179999999) )
+ sin ( radians(33.7835943) )
* sin( radians( latitude ) )
)
) AS distance, specials.id AS special_id, specials.name AS special_name, specials.photo
FROM vendors
JOIN specials ON vendor_id = specials.vendor_id
JOIN category_special ON specials.id = category_special.special_id
JOIN categories ON categories.id = category_special.category_id
WHERE category_special.category_id = 107
HAVING distance < 22
ORDER BY distance
LIMIT 0, 20
我的表结构如下:
vendors (id, name, latitude, longitude)
specials (id, vendor_id, name, description)
categories (id, name)
category_special (category_id, special_id) - pivot table
此特定查询的目标是返回与所需的category_id匹配的所有特价,其中供应商的位置在搜索人员的所需距离内。我尝试过不同的JOIN类型组合,但不断收到语法错误。我甚至在这里发现了类似的问题,但他们的解决方案都没有能够克服错误。简而言之,用户将发送包含category_id,纬度,经度和距离的POST请求以获得这些结果。非常感谢任何帮助。