简体   繁体   English

如何使用laravel查询构建器获取whereIn/whereBetween的总和?

[英]how to get sum with whereIn/whereBetween using laravel query builder?

I have getting wrong value from query.我从查询中得到了错误的值。 can anyone help me to correct my query in laravel project.任何人都可以帮助我纠正我在 laravel 项目中的查询。 mysql code : 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 code : 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'];
}

When i used querylog and got the query:当我使用 querylog 并得到查询时:

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)

I need to make it from and userid in (select userid from user where bank_id = 1 and usertype =1 OR usertype = 2) to 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) to and userid in (select userid from user where bank_id = 1 and (usertype =1 OR usertype = 2))

And can anyone suggest to minimize loading issue while running this query.任何人都可以建议在运行此查询时尽量减少加载问题。 i have almost 1M records in my database.我的数据库中有近 100 万条记录。
Thank you.谢谢你。

To get your expression inside brackets in Laravel ORM you need to use callback function inside where like this:要在 Laravel ORM 中获得括号内的表达式,您需要在where使用回调函数where如下所示:

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

But in your case you can also use shortest method:但在你的情况下,你也可以使用最短的方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM