如何在 Eloquent 中使用 now() ?

Fal*_*lco 1 php date eloquent slim-3

将 now() 与 Eloquent 结合使用的最佳方法是什么?我的意思是,是否有一个原生的 Eloquent 函数可以返回今天的日期?我正在使用 Slim 框架,对于这个查询,我找到的唯一解决方案是:

$now = date('Y/m/d H:i:s', time());

$articles = Article::where('created_at', '<', $now)
    ->orderBy('created_at', 'DESC')
    ->limit(10)
    ->get();
Run Code Online (Sandbox Code Playgroud)

有点乱,不是吗?我可以使用 Carbon,但它会产生额外的依赖性......

谢谢

rai*_*7ow 6

这里有两个选择:要么使用DB::raw方法让where方法按原样处理给定的表达式:

$articles = Article::where(DB::raw('created_at < NOW()'))
                    ->orderBy('created_at', 'DESC')
                    ->limit(10)
                    ->get();
Run Code Online (Sandbox Code Playgroud)

...或使用whereRaw方法:

$articles = Article::whereRaw('created_at < NOW()')
                    ->orderBy('created_at', 'DESC')
                    ->limit(10)
                    ->get();
Run Code Online (Sandbox Code Playgroud)

顺便说一句,Eloquent 有几个用于日期时间相关处理的辅助方法- whereDatewhereMonthwhereDay和。我真的不确定这些可以在这个特定情况下使用,但它们可能在其他地方有用。whereYearwhereTime