假设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