ayat
ayat

Reputation: 171

How to transform this raw SQL query into Laravel Eloquent

This raw SQL query is returning the expected result on my SQL console. Would you please help me to transform it into a Laravel Eloquent query?

SELECT * FROM `my_services` 
    WHERE `user_id` = 1 and `financial_year` = '2021-2022' 
    AND (service_type = 'Return' OR service_type = 'Correction Return') 
    ORDER BY id DESC LIMIT 1,1;

I have tried to implement it like the following.

MyService::where([
    'user_id' => $user->id, 
    'financial_year' => $request->financial_year,
    'financial_year' => '2021-2022'
])
->orWhere(['service_type' => 'Return'])
->orWhere(['service_type' => 'Correction Return'])
->orderBy("id", "desc")
->offset(1)
->limit(1)
->get();

Upvotes: 1

Views: 182

Answers (2)

Ramanath
Ramanath

Reputation: 530

Try this query -

MyService::where('user_id', 1)->where('financial_year', '2021-2022')->where(function($q) {
    $q->where('service_type', 'Return')->orWhere('service_type', 'Correction Return');
})->limit(1)->offset(1)->orderBy('id', 'DESC')->get();

Upvotes: 1

NoOorZ24
NoOorZ24

Reputation: 3222

From: https://laravel.com/docs/8.x/queries#limit-and-offset

Use ->skip(1) or ->offset(1) for offset

Use ->take(1) or ->limit(1) to limit count of returned results

Upvotes: 0

Related Questions