查询是否已加入2个模型

时间:2019-06-12 10:36:26

标签: mysql laravel laravel-5 eloquent

我正在使用Laravel 5,并且有2个具有关系的模型locationchauffeur

public function chauffeurs() { return $this->hasMany('App\Chauffeur'); }

public function location() { return $this->hasOne('App\Location', 'id', 'location_id'); }

这是我的查询,可以正常工作

"SELECT *, 
                    (6371 * acos(cos(radians(".$latitude.")) * cos(radians(latitude)) * cos(radians(longitude) - radians(".$longitude.")) + sin(radians(" . $latitude.")) * sin(radians(latitude)))) AS distance 
                    FROM `locations` AS l
                    JOIN `chauffeurs` AS c
                    ON (l.id = c.location_id)
                    HAVING distance < c.radius
                    ORDER BY distance ";

这是我到目前为止所拥有的

Chauffeur::select('*, (6371 * acos(cos(radians(1.492659)) * cos(radians(latitude)) * cos(radians(longitude) - radians(103.7413591)) + sin(radians(1.492659)) * sin(radians(latitude)))) AS distance ')
    ->join('Location', '`location`.`id`', '=', '`chauffeur`.`location_id`')
    ->havingRaw('distance < `chauffeur`.`radius`')
    ->get();

并收到此错误

`Syntax error or access violation: 1064 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 '.`492659)) * sin(radians(latitude))))` as `distance ` from `locations` inner joi'`

我将如何使用laravel模型进行相同的查询?知道我在做什么错或者有更好的方法吗?谢谢

1 个答案:

答案 0 :(得分:0)

使用DB :: raw();选择查询