Laravel,仅按日期过滤时间戳

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33231567/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:32:41  来源:igfitidea点击:

Laravel, filter timestamp by date only

phplaravel

提问by colouredFunk

I want to filter a table by user ID and the created_at field. The only thing is created_at is a timestamp, and I want to query by date only not time.

我想按用户 ID 和 created_at 字段过滤表。唯一的事情是 created_at 是一个时间戳,我只想按日期而不是时间查询。

So something like -

所以像 -

$messages = Message::where(['from' => $fromUser->id, 'created_at' => 'TODAY'S DATE'])->get();

回答by Hamid Parchami

$query->whereDate('created_at', '=', date('Y-m-d'));

or

或者

$query->whereDate('created_at', '=', Carbon::today()->toDateString());

回答by fantasitcalbeastly

The only way I know (in Laravel) to compare a DATEagainst created_atis to use whereRaw, so for your example, you'd use something like:

我知道(在Laravel)来比较的唯一途径DATE反对created_at是使用whereRaw,所以对于你的榜样,你会使用这样的:

Message::where(...)->whereRaw('DATE(created_at) = ?', [$today])->get();

You can find more information about Eloquent and it's other methods here

您可以在此处找到有关 Eloquent 及其其他方法的更多信息