1

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();
Karl Hill
  • 12,937
  • 5
  • 58
  • 95
ayat
  • 171
  • 8
  • https://stackoverflow.com/questions/35643192/laravel-eloquent-limit-and-offset – Ankita Dobariya Jun 29 '21 at 12:31
  • MyService::where('user_id', $user->id) ->where('financial_year', $request->financial_year) ->where(function($q) { $q->orWhereIn('service_type', ['Return', 'Correction Return']); })->orderBy("id", "desc")->skip(1)->take(1)->get(); – Ankita Dobariya Jun 29 '21 at 12:38

2 Answers2

1

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();
Ramanath
  • 510
  • 2
  • 12
  • financial_year has a single value there are no multiple years. so can you correct me with a single value I think it should be `->where('financial_year', '2021-2022')` – ayat Jun 29 '21 at 12:31
  • 1
    @ayat I've updated the query. Let me know if it works for you. – Ramanath Jun 29 '21 at 12:34
0

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

NoOorZ24
  • 2,914
  • 1
  • 14
  • 33