如何在Laravel中向查询构建器添加if语句

时间:2020-10-10 16:23:21

标签: laravel

在Laravel-5.8应用程序中,我具有用于生成请假余额的以下查询版本:

$leaveBalance = DB::table('hr_leave_types AS lt')
    ->leftJoin('hr_leave_type_details AS ltd', function ($join) use ($userCompany) {
        $join->on('ltd.leave_type_id', '=', 'lt.id')
            ->where('ltd.company_id', '=', $userCompany);
    })
    ->leftJoin('hr_leave_requests AS lr', function ($join) use ($userCompany, $userEmployee) {
        $join->on('lr.leave_type_id', '=', 'lt.id')
            ->where('lr.company_id', '=', $userCompany)
            ->where('lr.employee_id', '=', $userEmployee)
            ->whereYear('lr.commencement_date', '=', date('Y'))
            ->where('lr.leave_status', 4);
    })
    ->leftJoin('hr_employees AS e', function ($join) use ($userCompany, $userEmployee) {
        $join->on('e.id', '=', 'lr.employee_id')
            ->where('e.company_id', '=', $userCompany)
            ->where('e.id', '=', $userEmployee)
            ->where('e.employee_type_id', '=', 'ltd.employee_type_id');
    })
    ->where('lt.company_id', '=', $userCompany)
    ->select(
        'lt.leave_type_name as leaveCategory',
        'ltd.no_of_days as applicableLeave',
        DB::raw("IFNULL(SUM(lr.no_of_days),0) as approvedLeave")

    )
    ->groupBy('lt.leave_type_name', 'e.id')
    ->get();

这给了我结果:

LeaveCategory |适用于|已批准离开

但是我想在条件中添加一个条件

$leaveprorates = HrLeaveTypeDetail::select('is_prorate')->where('leave_type_id', $leavetypeid)->where('employee_type_id', $employeeemptypeid)->get();

foreach (leaveprorates as leaveprorate)

          if ($leaveprorate == 1) {
              if ($diff_in_months < 12) {
                  $applicableLeave = intval($authorizedleavedaysx * $diff_in_months / 12);
              } else {
                  $applicableLeave = HrLeaveTypeDetail::where('leave_type_id', $leaveType)->where('employee_type_id', $employeeemptypeid)->pluck('no_of_days')->first();
              }
          } else {
              $applicableLeave = HrLeaveTypeDetail::where('leave_type_id', $leaveType)->where('employee_type_id', $employeeemptypeid)->pluck('no_of_days')->first();
          }

如何在查询中为applyLeave添加此条件?

谢谢

0 个答案:

没有答案