【问题标题】:How to transform this raw SQL query into Laravel Eloquent如何将此原始 SQL 查询转换为 Laravel Eloquent
【发布时间】:2021-09-11 15:05:43
【问题描述】:

这个原始 SQL 查询在我的 SQL 控制台上返回预期结果。你能帮我把它转换成 Laravel Eloquent 查询吗?

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;

我已经尝试如下实现它。

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();

【问题讨论】:

  • MyService::where('user_id', $user->id) ->where('financial_year', $request->financial_year) ->where(function($q) { $q- >orWhereIn('service_type', ['Return', '修正返回']); })->orderBy("id", "desc")->skip(1)->take(1)->get() ;

标签: laravel eloquent laravel-query-builder


【解决方案1】:

发件人:https://laravel.com/docs/8.x/queries#limit-and-offset

使用->skip(1)->offset(1) 作为偏移量

使用->take(1)->limit(1) 限制返回结果的计数

【讨论】:

    【解决方案2】:

    试试这个查询 -

    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();
    

    【讨论】:

    • financial_year 有一个值,没有多个年份。所以你能用一个值纠正我吗?我认为它应该是->where('financial_year', '2021-2022')
    • @ayat 我已经更新了查询。让我知道它是否适合您。
    猜你喜欢
    • 2017-10-21
    • 2019-05-31
    • 2019-04-29
    • 2019-04-04
    • 2020-02-07
    • 2018-01-04
    • 2021-10-04
    • 1970-01-01
    • 2016-04-27
    相关资源
    最近更新 更多