MySQL 仅获取今天在 laravel 中创建的记录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33247908/
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-08-31 21:20:33  来源:igfitidea点击:

Get only records created today in laravel

mysqldateactiverecordwherelaravel-5.1

提问by TheWebs

How do I use the created_atfield to get only the records that were created today and no other day or time?

如何使用该created_at字段仅获取今天创建的记录,而不获取其他日期或时间?

I was thinking of a ->where('created_at', '>=', Carbon::now())But Im not sure that would work.

我在想一个->where('created_at', '>=', Carbon::now())但我不确定这会起作用。

回答by ashish

for Laravel 5.6+ users, you can just do

对于 Laravel 5.6+ 用户,你可以这样做

    $posts = Post::whereDate('created_at', Carbon::today())->get();

Happy coding

快乐编码

回答by Clean code

Use Mysqldefault CURDATEfunction to get all the records of the day.

使用Mysql默认CURDATE函数获取当天的所有记录。

    $records = DB::table('users')->select(DB::raw('*'))
                  ->whereRaw('Date(created_at) = CURDATE()')->get();
    dd($record);

Note

笔记

The difference between Carbon::nowvs Carbon::todayis just time.

Carbon::nowvs之间的区别Carbon::today只是时间。

e.g

例如

Date printed through Carbon::nowwill look like something:

打印出来的日期Carbon::now看起来像这样:

2018-06-26 07:39:10.804786 UTC (+00:00)

2018-06-26 07:39:10.804786 UTC (+00:00)

While with Carbon::today:

同时Carbon::today

2018-06-26 00:00:00.0 UTC (+00:00)

2018-06-26 00:00:00.0 UTC (+00:00)

To get the only records created today with nowcan be fetched as:

要获取今天创建的唯一记录,now可以获取为:

Post::whereDate('created_at', Carbon::now()->format('m/d/Y'))->get();

Post::whereDate('created_at', Carbon::now()->format('m/d/Y'))->get();

while with today:

同时与today

Post::whereDate('created_at', Carbon::today())->get();

Post::whereDate('created_at', Carbon::today())->get();

UPDATE

更新

As of laravel 5.3, We have default where clause whereDate / whereMonth / whereDay / whereYear

从 laravel 5.3 开始,我们有默认的 where 子句 whereDate / whereMonth / whereDay / whereYear

$users = User::whereDate('created_at', DB::raw('CURDATE()'))->get();

OR with DBfacade

或与DB门面

$users = DB::table('users')->whereDate('created_at', DB::raw('CURDATE()'))->get();

Usage of the above listed where clauses

上面列出的 where 子句的用法

$users = User::whereMonth('created_at', date('m'))->get();
//or you could also just use $carbon = \Carbon\Carbon::now(); $carbon->month;
//select * from `users` where month(`created_at`) = "04"
$users = User::whereDay('created_at', date('d'))->get();
//or you could also just use $carbon = \Carbon\Carbon::now(); $carbon->day;
//select * from `users` where day(`created_at`) = "03"
$users = User::whereYear('created_at', date('Y'))->get();
//or you could also just use $carbon = \Carbon\Carbon::now(); $carbon->year;
//select * from `users` where year(`created_at`) = "2017"

Query Builder Docs

查询生成器文档

回答by Itai Nathaniel

If you are using Carbon (and you should, it's awesome!) with Laravel, you can simply do the following:

如果你在 Laravel 中使用 Carbon(你应该这样做,它太棒了!),你可以简单地执行以下操作:

->where('created_at', '>=', Carbon::today())

Besides now()and today(), you can also use yesterday()and tomorrow()and then use the following:

除了now()today(),你也可以使用yesterday()tomorrow()再使用以下命令:

  • startOfDay()/endOfDay()
  • startOfWeek()/endOfWeek()
  • startOfMonth()/endOfMonth()
  • startOfYear()/endOfYear()
  • startOfDecade()/endOfDecade()
  • startOfCentury()/endOfCentury()
  • startOfDay()/endOfDay()
  • startOfWeek()/endOfWeek()
  • startOfMonth()/endOfMonth()
  • startOfYear()/endOfYear()
  • startOfDecade()/endOfDecade()
  • startOfCentury()/endOfCentury()

回答by Mahmoud Zalt

with carbon:

含碳:

return $model->where('created_at', '>=', \Carbon::today()->toDateString());

without carbon:

无碳:

return $model->where('created_at', '>=', date('Y-m-d').' 00:00:00');

回答by Sandyandi N. dela Cruz

You can use whereRaw('date(created_at) = curdate()')if timezone is not a concern or whereRaw('date(created_at) = ?', [Carbon::now()->format('Y-m-d')] )otherwise.

whereRaw('date(created_at) = curdate()')如果时区不是问题,您可以使用whereRaw('date(created_at) = ?', [Carbon::now()->format('Y-m-d')] )

Since the created_atfield is a timestamp, you need to get only the date part of it and ignore the time part.

由于该created_at字段是时间戳,因此您只需获取其中的日期部分,而忽略时间部分。

回答by Mokhamad Rofi'udin

$today = Carbon\Carbon::now()->format('Y-m-d').'%';
->where('created_at', 'like', $today);

Hope it will help you

希望它会帮助你

回答by chebaby

Laravel ^5.6 - Query Scopes

Laravel ^5.6 - 查询范围

For readability purposes i use query scope, makes my code more declarative.

出于可读性目的,我使用查询范围,使我的代码更具声明性。

scope query

范围查询

namespace App\Models;

use Illuminate\Support\Carbon;
use Illuminate\Database\Eloquent\Model;

class MyModel extends Model
{
    // ...

    /**
     * Scope a query to only include today's entries.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeCreatedToday($query)
    {
        return $query->where('created_at', '>=', Carbon::today());
    }

    // ...
}

example of usage

用法示例

MyModel::createdToday()->get()

SQL generated

生成的 SQL

Sql      : select * from "my_models" where "created_at" >= ?

Bindings : ["2019-10-22T00:00:00.000000Z"]

回答by Kamiyabali

I've seen people doing it with raw queries, like this:

我见过有人用原始查询来做这件事,像这样:

$q->where(DB::raw("DATE(created_at) = '".date('Y-m-d')."'"));

Or without raw queries by datetime, like this:

或者不按日期时间进行原始查询,如下所示:

$q->where('created_at', '>=', date('Y-m-d').' 00:00:00'));

Luckily, Laravel Query Builder offers a more Eloquent solution:

幸运的是,Laravel Query Builder 提供了一个更 Eloquent 的解决方案:

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

Or, of course, instead of PHP date() you can use Carbon:

或者,当然,您可以使用Carbon代替 PHP date() :

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

It's not only whereDate. There are three more useful functions to filter out dates:

这不仅是 whereDate。还有三个更有用的函数可以过滤掉日期:

$q->whereDay('created_at', '=', date('d'));
$q->whereMonth('created_at', '=', date('m'));
$q->whereYear('created_at', '=', date('Y'));

回答by hsul4n

No need to use Carbon::todaybecause laravel uses function now() instead as a helper function

不需要使用,Carbon::today因为 laravel 使用函数 now() 作为辅助函数

So to get any records that have been created today you can use the below code:

因此,要获取今天创建的任何记录,您可以使用以下代码:

Model::whereDay('created_at', now()->day)->get();

You need to use whereDateso created_at will be converted to date.

您需要使用whereDate这样 created_at 将转换为日期。

回答by Paul Kiarie

$records = User::where('created_at' = CURDATE())->GET()); print($records);

$records = User::where('created_at' = CURDATE())->GET()); 打印($记录);