使用Laravel对计算列执行查询

时间:2017-01-29 12:52:04

标签: mysql laravel laravel-5 eloquent

我想使用Laravel的Eloquent模型在PHP中执行以下SQL语句:

SELECT *, (3959 * acos(cos(radians(37)) * cos(radians(lat)) * cos(radians(lng) - radians(-122)) + sin(radians(37)) * sin(radians(lat )))) AS distance
FROM example_retailers
HAVING distance < 1000
ORDER BY distance
OFFSET 4
LIMIT 3;

我正在努力将其转化为Laravel的Eloquent模型(主要是计算专栏)。

这是我到目前为止所做的:

ExampleRetailer::
    // TODO: add calculated row
    where('distance', '<', 100)
    ->orderBy('distance')
    ->skip(4)
    ->limit(3)
    ->get();

2 个答案:

答案 0 :(得分:2)

您可以使用原始查询(source

DB::table('example_retailers')
->select(DB::raw('*, (3959 * acos(cos(radians(37)) * cos(radians(lat)) * cos(radians(lng) - radians(-122)) + sin(radians(37)) * sin(radians(lat )))) AS distance'))
->having('distance', '<', 100)
->orderBy('distance')
->skip(4)
->limit(3)
->get();

答案 1 :(得分:-1)

如果仅使用SQL创建新行:

SELECT *,

CASE WHEN(3959 * acos(cos(弧度(37))* cos(弧度(lat))* cos(弧度(lng) - 弧度(-122))+ sin(弧度(37))* sin(弧度(lat))))&lt; 100那么结束为NewRow


FROM example_retailers