Laravel在月份和年份获得记录

时间:2016-04-19 09:19:07

标签: php mysql laravel

我正在使用Laravel 5.2

我有一个数据库表schedules

id    name     start_date    end_date
1     AAAAA    2016-01-01    2016-12-31
2     BBBBB    2016-02-01    2016-03-31
3     CCCCC    2016-04-01    2016-06-12
4     DDDDD    2016-04-18    2016-07-15
5     EEEEE    2016-03-15    2016-04-14
6     FFFFF    2016-05-01    2016-08-26

现在,我想要获取resides in current monthApril-2016的时间表记录。结果应该是

id    name     start_date    end_date
1     AAAAA    2016-01-01    2016-12-31
3     CCCCC    2016-04-01    2016-06-12
4     DDDDD    2016-04-18    2016-07-15
5     EEEEE    2016-03-15    2016-04-14

我尝试过使用,

Schedule::whereDate('start_date', '<=', '2016-04-01')
->whereDate('end_date', '>=', '2016-04-30')
->get();

但它排除了id 14的记录。

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:2)

此代码通过您的标准。试试吧。

DB::select(DB::raw("SELECT * FROM schedules WHERE start_date <= '2016-04-30' AND end_date >= '2016-04-01'"))

或者用Eloquent:

Schedule::where('start_date','<=', '2016-04-30')->where('end_date','>=', '2016-04-01')->get();

答案 1 :(得分:1)

检查包容性和&amp;重叠日期范围:

Schedule::where(function($q) use($start_date,$end_date) {
    //Inclusive Date Range
    return $q->orWhere(function($q) use($start_date,$end_date) {
        return $q->where('start_date','>=',$start_date)
            ->where('end_date','<=',$end_date);
    })
    //Overlapping Date Range
    ->orWhere(function($q) use($start_date,$end_date) {
        return $q->where('start_date','<=',$start_date)
            ->where('end_date','>=',$end_date);
    });
})
->get();