我很难将这个子查询转换为laravel。有人可以帮我转换这个长查询
SELECT
rescue_units.id as 'rescue_units_id',
name,
address,
lat,
lng,
email,
type,
status,
( 6371 * acos( cos( radians(10.3099568) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(123.8934193) ) + sin( radians(10.3099568) ) * sin( radians( lat ) ) ) ) AS distance
FROM rescue_units
WHERE rescue_units.id = ANY (
SELECT ru_id
FROM ru_ec
WHERE ec_id = (
SELECT id
FROM emergency_codes
WHERE ID = 6
)
)
AND
status = 1
order by distance
编辑: 这是我到目前为止所尝试过的。
$markersByRadius = RescueUnit::select(
DB::raw("rescue_units.id as 'rescue_units_id', name, address, lat, lng, email, type, status,
( 6371 * acos( cos( radians(?) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(?) ) + sin( radians(?) ) * sin( radians( lat ) ) ) ) AS distance
FROM rescue_units WHERE rescue_units.id = ANY (SELECT ru_id FROM ru_ec WHERE ec_id = (SELECT id FROM emergency_codes WHERE ID = ?)) AND status = 1 order by distance"))
->take($limit)
->setBindings([$lat, $lng, $lat, $ec_id])
->get();
return $markersByRadius;
这就是错误:
SQLSTATE[42000]: 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 'WHERE rescue_units.id = ANY (SELECT ru_id FROM ru_ec WHERE ec_id = (SELECT id FR' at line 3 (SQL: select rescue_units.id as 'rescue_units_id', name, address, lat, lng, email, type, status, ( 6371 * acos( cos( radians(10.3099568) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(123.8934193) ) + sin( radians(10.3099568) ) * sin( radians( lat ) ) ) ) AS distance WHERE rescue_units.id = ANY (SELECT ru_id FROM ru_ec WHERE ec_id = (SELECT id FROM emergency_codes WHERE ID = 6)) AND status = 1 from `rescue_units` order by `distance` asc limit 3)
答案 0 :(得分:0)
请检查此天气未经测试但应该可以使用。 只有你做错的部分是sub query。
$markersByRadius = RescueUnit::select(
DB::raw("rescue_units.id as 'rescue_units_id', name, address, lat, lng, email, type, status,
( 6371 * acos( cos( radians(?) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(?) ) + sin( radians(?) ) * sin( radians( lat ) ) ) ) AS distance"))
->where('rescue_units.id', function($query)
{
$query->select(DB::raw('ru_id'))
->from('ru_ec')
->where('ru_ec.ec_id', function($query)
{
$query->select(DB::raw('id'))
->from('emergency_codes')
->where('ID = ?')
->where('status','1')
->orderBy('distance', 'ASC');
}));
})
->take($limit)
->setBindings([$lat, $lng, $lat, $ec_id])
->get();