如何在laravel5中使用原始查询在leftjoin中使用多个条件

时间:2017-07-21 06:25:34

标签: php mysql laravel-5.2

我需要加入两个表来获取具有多个条件的数据,但是在leftjoin但是 我收到这个错误。 没有足够的on子句参数我正在使用laravel5.2。如何使用带有leftjoin多条件的原始查询。

    $activityDetail = DB::table('table1 as UA')
        ->selectRaw('SUM(UA.total_calory) as total_calory,
            SUM(UA.flight_descend) as flight_descend,date('.$tz_start_date.') as start_date')
        ->leftjoin('table2 as LC',function($join) use($tz_lccreated_date,$dateRange){
                $join->on('LC.user_id_fk','=','UA.user_id_fk');
                $join->on('LC.is_active','=',DB::raw('1'));
                $join->on(' date('.DB::raw($tz_lccreated_date).') '.DB::raw($dateRange));
            })
            ->whereRaw(' date('.$tz_start_date.') '.$dateRange)
            ->where('UA.user_id_fk','=',base64_decode($params['uid']))
            ->groupBy(DB::raw('date('.$tz_start_date.')'))
            ->get();

Raw query is 

select SUM(UA.total_calory) as total_calory,
SUM(UA.flight_descend) as flight_descend,
date(CONVERT_TZ(UA.start_date,"+00:00","+05:30")) as start_date 
from `table1` as `UA` 
left join `table2` as `LC` 
on `LC`.`user_id_fk` = `UA`.`user_id_fk` and `LC`.`is_active` = 1
and `date(CONVERT_TZ(LC`.`created_date,"+00:00","+05:30"))` = `current_date` 
where date(CONVERT_TZ(UA.start_date,"+00:00","+05:30")) = current_date
and `UA`.`user_id_fk` = 411 
group by date(CONVERT_TZ(UA.start_date,"+00:00","+05:30"))

1 个答案:

答案 0 :(得分:0)

I have resolved my problem, after a lots of analysis, i am not getting any kind of solution of raw  query in join clause then i am using subquery and resolve my problem.

$mannualLoggedQuery = 'IFNULL((select sum(calory) as cal from table2 as LC where LC.user_id_fk = "'.base64_decode($params['uid']).'" and date('.$tz_lccreated_date.')'.$dateRange.'),0)';


$activityDetail = DB::table('table1 as UA')->selectRaw('SUM(UA.total_calory) + '.$mannualLoggedQuery.' as total_calory,

                                    date('.$tz_start_date.') as start_date')
                                    ->where('UA.user_id_fk','=',base64_decode($params['uid']))
                                    ->whereRaw('date('.$tz_start_date.') '.$dateRange)
                                    ->groupBy(DB::raw('date('.$tz_start_date.')'))
                                    ->get();