Yahya Uddin
Yahya Uddin

Reputation: 28951

Perform query on a calculated column using Laravel

I want to perform the following SQL statement in PHP using Laravel's Eloquent model:

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;

I am struggling to translate this into a Laravel's Eloquent Model (mainly the calculated column).

This is what I have so far:

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

Upvotes: 0

Views: 3658

Answers (2)

Raphael Rohner
Raphael Rohner

Reputation: 21

If it's only to make a new row using SQL:

SELECT *, CASE WHEN (3959 * acos(cos(radians(37))
                          * cos(radians(lat))
                          * cos(radians(lng) - radians(-122))
                          + sin(radians(37))
                          * sin(radians(lat )))) < 100 THEN END AS NewRow
FROM example_retailers

Upvotes: -1

Erkan &#214;zk&#246;k
Erkan &#214;zk&#246;k

Reputation: 891

You can use raw queries (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();

Upvotes: 2

Related Questions