Laravel 5.0使用请求参数加入子查询

时间:2016-11-08 16:24:29

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

我正在尝试创建一个非常复杂的查询,我尽可能简化它(2个选择语句,连接到主查询),下面的代码,仅适用于没有“日期”参数在请求中发送,当参数发送时,我收到错误“SQLSTATE [HY000]:一般错误:2031”

我认为问题出现在toSql()方法中,但我不知道还能使用什么 解决这个问题?

更新:我需要保留leftJoin方法,所以我不能使用mergeBindings方法

    // 1st select statement
    $earnQuery = DB::Table('san_charity_point_earn')->select('charity_id','earn_date',DB::raw('count(user_id) as users,sum(points) as earn_points,count(transaction_id) as earn_trans'))
    ->where(function($q) use($request){
        // filter paramters
        if($request->has("from")){
            $q->where("earn_date",">=",$request->from);
        }

        if($request->has("to")){
           $q->where("earn_date","<=",$request->to);
        }
    })
    ->groupBy('charity_id')
    ->toSql();


    // 2nd select statement
    $redeemQuery = DB::Table('san_charity_point_redeem')->select('charity_id','redeem_date',DB::raw('sum(points) as redeem_points,count(transaction_id) as redeem_trans'))
    ->where(function($q) use($request){
        // filter paramters
        if($request->has("from")){
            $q->where("redeem_date",">=",$request->from);
        }

        if($request->has("to")){
           $q->where("redeem_date","<=",$request->to);
        }
    })
    ->groupBy('charity_id')
    ->toSql();


  //full Query  
  $charities = DB::table('san_charity')->select('san_charity.charity_id','title_ar','title_en',DB::raw('
        COALESCE(users,0) as users, 
        COALESCE((earn_trans+redeem_trans),0) as transactions, 
        COALESCE(earn_points,0) as earn_points,
        COALESCE(redeem_points,0) as redeem_points'))
        ->leftJoin(DB::raw('('.$earnQuery.') earn'),function($join){
            $join->on('earn.charity_id','=','san_charity.charity_id');
        })
        ->leftJoin(DB::raw('('.$redeemQuery.') redeem'),function($join){
            $join->on('redeem.charity_id','=','san_charity.charity_id');
        })
        ->get();

0 个答案:

没有答案