【问题标题】:how to get sum with whereIn/whereBetween using laravel query builder?如何使用 laravel 查询生成器获取 whereIn/whereBetween 的总和?
【发布时间】:2020-12-17 10:20:29
【问题描述】:

我从查询中得到错误的值。谁能帮我纠正我在 laravel 项目中的查询。 mysql代码:

select SUM(amount) as total from `sales` 
where `bankid` = 1 
and `month` = 8 
and `year` = 2020
and userid in (select userid from user where bank_id=2 AND (usertype=1 OR usertype=2))

Laravel 代码:

function test($bank_id,$usertype,$month=NULL,$year=NULL){
    $query = Sales::query();
    if(is_numeric($bank_id)){
        $query->where('bankid',$bank_id);
    }
    if($month)
    $query = $query->where('month', $month);
    
    if($year)
    $query = $query->where('year', $year);

    $query = $query->select(DB::raw("SUM(amount) as total"));
    if(is_numeric($usertype)){
        $query->whereIn('userid',function ($query) use($bank_id,$usertype) {
            $query->select(DB::raw('userid'))
            ->from('user');            
            if(is_numeric($bank_id)){
                $query->where('bank_id',$bank_id);
            }                 
            if($usertype==1){
               // $query->whereBetween('usertype', [1, 2]);
                $query->where('usertype', 1);
                $query->orWhere('usertype', 2);
            } else {
                $query->where('usertype',$usertype);
            }
        });
    } 
    return $query->get()->toarray()[0]['total'];
}

当我使用查询日志并得到查询时:

DB::connection()->enableQueryLog(); 
dd($query->toSql(), $query->getBindings());

select SUM(amount) as total from `slaes` 
where `bankid` = 1 
and `month` = 8 
and `year` = 2020 
and `userid` in (select userid from `user` where `bank_id` = 1 and `usertype` =1 OR `usertype` = 2)

我需要从and userid in (select userid from user where bank_id = 1 and usertype =1 OR usertype = 2)and userid in (select userid from user where bank_id = 1 and (usertype =1 OR usertype = 2))

任何人都可以建议在运行此查询时尽量减少加载问题。我的数据库中有近 100 万条记录。
谢谢。

【问题讨论】:

    标签: php mysql laravel-5 laravel-query-builder


    【解决方案1】:

    要将表达式放在 Laravel ORM 中的括号内,您需要在 where 中使用回调函数,如下所示:

    $query->where(function($query) {
      return $query
        ->where('usertype', 1)
        ->orWhere('usertype', 2);
    });
    

    但在你的情况下,你也可以使用最短的方法:

    $query->whereIn('usertype', [1,2]);
    

    【讨论】:

    • 我试过 $query->whereIn('usertype', [1,2]);还。但是返回响应也需要很长时间。
    猜你喜欢
    • 1970-01-01
    • 2018-11-25
    • 2021-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-28
    • 1970-01-01
    • 2017-04-13
    相关资源
    最近更新 更多