mardi 8 novembre 2016

Laravel 5.0 Join Sub Query With Request Paramters

I'm trying to create a very complex query, I've simplified it as much as possible (2 select statements, are concatenated to the main query), the code below, works only If there are no "date" parameters sent in the request, When parameters sent, I got an error "SQLSTATE[HY000]: General error: 2031"

I think the problem is in toSql() method, but I don't know what else could I use to solve that?

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



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire