假設created_at是正常datetime
場。
如果您需要從當月開始的所有文章,您可以結合使用一些不錯的碳幫助器,因此在這種情況下不需要使用閉包。
例子:
// Garble or empty inputs will throw an Exception in Carbon
try {
// this will create a Carbon object or Carbon will throw an exception
$date = Carbon::parse(request()->input('month'));
$articles = NewsItem::whereBetween('created_at', [
$date->startOfMonth()->toDateTimeString(),
$date->endOfMonth()->toDateTimeString(),
])->get();
} catch(\Exception $e) {
// gracefully handle Exception
dd($e->getMessage());
}
因此,使用這裏封閉在這裏不需要。
如果你想看到如何使用它們的示例,請參閱Laravel query parameter grouping
一些附加實例閉包:
在你的情況,而不是之間使用,你也可以組2在這樣的關閉:
// Garble or empty inputs will throw an Exception in Carbon
try {
// this will create a Carbon object or Carbon will throw an exception
$date = Carbon::parse(request()->input('month'));
$articles = NewsItem::where('created_at', function($query) use($date) {
$query
->where('created_at', '>=', $date->startOfMonth()->toDateTimeString())
->where('created_at', '<=', $date->endOfMonth()->toDateTimeString());
})->get();
} catch(\Exception $e) {
// gracefully handle Exception
dd($e->getMessage());
}
我假設news_items表的created_at字段是日期時間字段? – Robert