【问题标题】:Laravel - How to calculate number of holidays between two daysLaravel - 如何计算两天之间的假期数
【发布时间】:2020-04-11 22:09:32
【问题描述】:

在我的 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 之间的假期数。

谢谢。

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:
       $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);
      

      希望这会有所帮助..

      【讨论】:

        猜你喜欢
        • 2022-08-12
        • 1970-01-01
        • 2022-01-13
        • 2020-08-21
        • 2012-02-26
        • 2010-10-07
        • 1970-01-01
        相关资源
        最近更新 更多