简体   繁体   中英

How to Use 'DATEADD' function in Laravel join?

I've a Laravel 4 join as given below:

return DB::table(Location::getTableName() . ' as l')->where('l.company_id', $companyId)
        ->join(User::getTableName() . ' as u', 'u.location_id', '=', 'l.id')->whereIn('l.id', $locationsId)
        ->join(UserTimeline::getTableName() . ' as ut', 'ut.user_id', '=', 'u.id')
        ->join(Status::getTableName() . ' as s', 's.id', '=', 'ut.status_id')
        ->select(
            'l.name as location_name',
            'u.first_name as user_first_name',
            'u.last_name as user_last_name',
            'u.email as user_email',
            'ut.started_at as timeline_started_at',
            'ut.finished_at as timeline_finished_at',
            's.id as status_id',
            's.label as status_label'
        )
        ->orderBy('ut.id', 'asc')
        ->skip($from)
        ->limit($limit)
        ->get();

I've to detect the user's timezone and compute the difference from GMT as a number which might be +5 for Pakistan and +5.5 for India. Now the problem with me is that I'm exporting the data of this join in a CSV file. I've to add hours as a number in 'timeline_started_at' and 'timeline_finished_at'. I've searched and found that 'DATEADD' method of SQL can add or subtract the hours.

The real problem is that I don't know that where in the above join I should use 'DATEADD' function in my Laravel join.

Can someone plz help me in this regard?????????

You can use DB::raw() to add sql functions to your query.

For example:

$test = DB::table('test')->where(DB::raw('DATE_ADD(created_at, 5)'), '<', $date)->get();

You can use something like that:

return DB::table(Location::getTableName() . ' as l')->where('l.company_id', $companyId)
        ->join(User::getTableName() . ' as u', 'u.location_id', '=', 'l.id')->whereIn('l.id', $locationsId)
        ->join(UserTimeline::getTableName() . ' as ut', 'ut.user_id', '=', 'u.id')
        ->join(Status::getTableName() . ' as s', 's.id', '=', 'ut.status_id')
        ->select(
            'l.name as location_name',
            'u.first_name as user_first_name',
            'u.last_name as user_last_name',
            'u.email as user_email',
            'DATE_ADD(ut.started_at, INTERVAL '.$var.' HOUR) as timeline_started_at',
            'DATE_ADD(ut.finished_at, INTERVAL '.$var.' HOUR) as timeline_finished_at',
            's.id as status_id',
            's.label as status_label'
        )
        ->orderBy('ut.id', 'asc')
        ->skip($from)
        ->limit($limit)
        ->get();

Where $var represents the number of hours.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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