Laravel-如何计算两天之间的假期数

时间:2020-04-11 11:24:40

标签: laravel eloquent

在我的Laravel-5.8应用程序中,我想提取数据库中另一个表中两个日期之间的假期数。我基本上有2张桌子:

  1. hr_leave_requests

  2. hr_holidays

     class HrHoliday extends Model
     {
      protected $table = 'hr_holidays';
       protected $fillable = [
      'holiday_name',
      'holiday_date',
      'created_at',
     ];
    }
    
    class HrLeaveRequest extends Model
    {
        protected $table = 'hr_leave_requests';
        protected $fillable = [
          'id',
          'commencement_date',
          'resumption_date',
        ];
    }
    

在我的控制器中,我有:

        $commencementDate   = Carbon::parse($request->commencement_date);
        $resumptionDate     = Carbon::parse($request->resumption_date);
        $holidays = DB::table('hr_holidays')->select('holiday_date')->whereYear('created_at', '=', date('Y'))->get();

        $commencementDate  and  $resumptionDate  are from hr_leave_requests

如何完成此查询:

$holidays = DB::table('hr_holidays')->select('holiday_date')->whereYear('created_at', '=', date('Y'))->get();

获取介于$ commencementDate和$ resumptionDate之间的假期数。

谢谢。

2 个答案:

答案 0 :(得分:0)

您应该可以在查询中访问whereBetween()

$holidays = DB::table('hr_holidays')->select('holiday_date')->whereBetween('holiday_date', [$commencementDate, $resumptionDate])->whereYear('created_at', '=', date('Y'))->get(); 

答案 1 :(得分:0)

 $commencementDate = Carbon::parse($request->commencement_date)
            ->startOfDay()        // 2020-01-01 00:00:00.000000
            ->toDateTimeString(); // 2020-01-01 00:00:00

 $resumptionDate = Carbon::parse($request->resumption_date)
            ->endOfDay()          // 2020-04-11 23:59:59.000000
            ->toDateTimeString(); // 2020-04-11 23:59:59

$holidays  = HrHoliday::whereHas('HrLeaveRequest', function ($q) use ($from, $to) {
            $q->whereBetween('created_at', [$from, $to]);
        })->get();


    dd($holidays);

希望这会有所帮助。