【问题标题】:Laravel get employee have been hired for n monthsLaravel get 员工已入职 n 个月
【发布时间】:2020-09-09 10:16:12
【问题描述】:

假设在我的员工表中,我有一个列“hire_date”,我想要在“hire_date”之前拥有 1-3 个月任期的员工或只有 3 个月大的员工。

我试过了:

Employee::whereDate('hire_date', '<=', Carbon::now()->subMonths(3))
          ->orderBy('hire_date', 'desc')
          ->get();

但它会返回所有员工。

我打印了原始查询,它只是从当前日期返回 3 个月,然后获取记录。

date(`hire_date`) <= 2020-02-22 //whereDate('hire_date', '<=', Carbon::now()->subMonths(3)

我做错了什么? 有什么想法可以实现这一目标吗?

示例: Jhon 一名员工于 2020 年 2 月 1 日被一家公司聘用。 因此,当他在公司完成 3 个月的工作时,我想通过获取他的记录来做一些事情。

【问题讨论】:

    标签: php mysql sql laravel eloquent


    【解决方案1】:

    问题: Jhon 一名员工于 2020 年 2 月 1 日被一家公司聘用。因此,当他在公司完成 3 个月的工作时,我想通过获取他的记录来做一些事情。

    您的问题的解决方案是,

    $datetime = new DateTime('NOW'); //Current date
    $datetime->modify('- 3 months'); //Date before 3 months
    $backDate = datetime->format('Y-m-d'); //Format date
    
    $employees = Employee::whereDate('hire_date', $backDate)
                              ->orderBy('hire_date', 'desc')
                              ->get();
    

    【讨论】:

    • 如果current date - 3 months是入职日期,这只会工作一次,如果超过3个月就不会工作,我想再次获取员工的记录。
    【解决方案2】:

    因此,对于每个月的第一天和最后一天之间雇用的所有人员

    Employee::whereDate('hire_date', '>=', Carbon::now()->subMonths(3)->firstOfMonth())
              ->whereDate('hire_date', '<=', Carbon::now()->subMonths(3)->lastOfMonth())  
              ->orderBy('hire_date', 'desc')
              ->get();
    

    这样

    date(`hire_date`) <= '2020-02-1' AND date(`hire_date`) >= '2020-02-29'
    

    【讨论】:

    • 我很困惑,你到底想要什么,你能举个例子吗
    • 用例子更新问题。
    • 他们都是在月初入职的吗?
    • 在我的情况下,日期无关紧要月份,但您可以将其考虑在内。
    • 然后尝试新查询
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-19
    • 1970-01-01
    • 1970-01-01
    • 2017-01-24
    • 2014-06-28
    • 2023-04-01
    相关资源
    最近更新 更多