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

时间:2015-10-20 22:28:06

标签: mysql date activerecord where laravel-5.1

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

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

13 个答案:

答案 0 :(得分:50)

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

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

注意

Carbon::nowCarbon::today之间的差异只是时间。

e.g

通过Carbon::now打印的日期看起来像是:

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

使用Carbon::today

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

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

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

today

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

<强>更新

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

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

OR与DB门面

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

使用上面列出的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

答案 1 :(得分:49)

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

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

快乐编码

答案 2 :(得分:33)

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

menudeleted = MessMenu.objects.filter( day__lt = timezone.now())
    for m in menudeleted:
        m.delete()
menu = MessMenu.objects.all()

->where('created_at', '>=', Carbon::today()) now()外,您还可以使用today()yesterday(),然后使用以下内容:

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

答案 3 :(得分:11)

含碳:

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

没有碳:

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

答案 4 :(得分:5)

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

由于created_at字段是时间戳,因此您只需要获取日期部分并忽略时间部分。

答案 5 :(得分:2)

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

希望它能帮到你

答案 6 :(得分:0)

以下代码对我有用

  <script type="text/x-mathjax-config">
    MathJax.Ajax.config.path["Contrib"] = "//cdn.mathjax.org/mathjax/contrib";
    MathJax.Hub.Config({
        TeX: {  extensions: ["color.js","AMSmath.js","AMSsymbols.js","[Contrib]/xyjax/xypic.js"] },
        tex2jax: { inlineMath: [['$','$'], ["\\(","\\)"]] }
    });
  </script>

答案 7 :(得分:0)

简单的解决方案:

using Luxor, Colors
Drawing(1200, 1400)

origin()
cols = diverging_palette(60, 120, 20) # hue 60 to hue 120
background(cols[1])
setopacity(0.7)
setline(2)

# circumradius of 500
ngon(0, 0, 500, 8, 0, :clip)

答案 8 :(得分:0)

Carbon::today() 将返回如下内容:2021-08-06T00:00:00.000000Z,因此使用 Model::where('created_at', Carbon::today()) 将仅返回在当前日期上午 12:00 创建的记录。

改用Model::where('created_at', '>=', Carbon::today())

答案 9 :(得分:-1)

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

答案 10 :(得分:-1)

Laravel ^ 5.6-查询范围

出于可读性考虑,我使用query scope,使我的代码更具声明性。

范围查询

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());
    }

    // ...
}

用法示例

MyModel::createdToday()->get()

生成的SQL

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

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

答案 11 :(得分:-1)

我见过人们在处理原始查询,例如:

//this is my code: 
<?php
    $con=mysqli_connect("localhost","root","","ban_giay");
    mysqli_set_charset('$con','UTF8');
?>//

或者在日期时间之前没有原始查询,例如:

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

幸运的是,Laravel查询生成器提供了一种更为口才的解决方案:

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

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

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

不仅日期在哪里。还有另外三个有用的功能可以过滤日期:

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

答案 12 :(得分:-2)

无需使用Carbon::today,因为laravel使用now()函数代替了辅助函数

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

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

您需要使用whereDate,以便created_at会转换为日期。