我有以下查询:
$clinics = \DB::select('SELECT * FROM
(SELECT *,
(100 * acos(cos(radians(' . $lat . ')) * cos(radians(lat)) *
cos(radians(lng) - radians(' . $lng . ')) +
sin(radians(' . $lat . ')) * sin(radians(lat))))
AS distance
FROM clinics) AS distances
WHERE distance < 100
ORDER BY distance')
->join('countries', 'clinics.country_id', '=', 'countries.id');
当我运行它时,我收到以下错误:
Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_ERROR)
Call to a member function join() on array
是否可以使用此查询执行 JOIN ? 我尝试在select查询中添加 JOIN ,但我收到错误:
Column not found: 1054 Unknown column 'clinics.country_id' in 'on clause' (SQL: SELECT * FROM (SELECT *, (100 * acos(cos(radians(43.1557012)) * cos(radians(lat)) * cos(radians(lng) - radians(22.5856811)) + sin(radians(43.1557012)) * sin(radians(lat)))) AS distance FROM clinics) AS distances JOIN countries ON countries.id = clinics.country_id WHERE distance < 100 ORDER BY distance)
有问题的查询:
$clinics = \DB::select('SELECT * FROM
(SELECT *,
(100 * acos(cos(radians(' . $lat . ')) * cos(radians(lat)) *
cos(radians(lng) - radians(' . $lng . ')) +
sin(radians(' . $lat . ')) * sin(radians(lat))))
AS distance
FROM clinics) AS distances
JOIN countries ON countries.id = clinics.country_id
WHERE distance < 100
ORDER BY distance');
答案 0 :(得分:2)
从我所看到的,子查询不是必需的,您可以将查询转换为Laravel表示法,如下所示:
$clinics = Clinic::join('countries', 'countries.id', '=', 'clinics.country_id')
->selectRaw('clinics.*, countries.*, (
100 * acos(
cos(radians(?)) *
cos(radians(lat)) *
cos(radians(lng) - radians(?)) +
sin(radians(?)) * sin(radians(lat))
)
) as distance', [$lat, $lng, $lat])
->having('distance', '<', 100)
->orderBy('distance')
->get();
您可能希望明确列出要为countries
表选择的列,因为使用countries.*
您将覆盖id
表的clinics
列。我添加了countries.*
,因为我想这是你加入表后想要做的事情。