将mysql查询转换为Laravel的DB:Query Builder

时间:2018-09-07 05:55:24

标签: laravel query-builder laravel-query-builder

我使用SQL工具在数据库上尝试了此操作。运行良好。但是现在我正在努力将其实现到我的数据库:查询生成器。任何帮助或建议将对我感激不尽。如果需要更多详细信息,请发表评论。我将继续关注

SELECT u.*, (6371 * acos(cos(radians(22.559648)) * cos(radians(`lat`)) * cos(radians(`lng`) - radians(88.415552)) + sin(radians(22.559648)) * sin(radians(`lat`)))) AS distances 
FROM users AS u
JOIN locations AS l ON `u`.`location_id` = `l`.`id` 
HAVING distances < 32.688888 
ORDER BY distances DESC

1 个答案:

答案 0 :(得分:1)

@JinalSomaiya 我更改了以下内容并正常工作。

 ->having('distances', '<', 32.688888])

->having('distances', '<', [32.688888])

->join('locations as l', 'l.id', '=', 'users. location_id')

->join('locations as l', 'users.location_id', '=', 'l.id')

最终查询:

修改

DB::table('users')
            ->join('locations as l', 'users.location_id', '=', 'l.id')
            ->select('users.*', DB::raw('(6371 * acos(cos(radians(22.559648)) * cos(radians(`lat`)) * cos(radians(`lng`) - radians(88.415552)) + sin(radians(22.559648)) * sin(radians(`lat`)))) as distances'))
            ->having('distances', '<', 32.688888)
            ->orderBy('distances', 'DESC')
            ->get();