【问题标题】:How can I select all Eloquent models from a MySQL database inserted today, within the last week or the last month?如何从今天、上周或上个月插入的 MySQL 数据库中选择所有 Eloquent 模型?
【发布时间】:2014-07-23 14:22:53
【问题描述】:

我有一个 Eloquent 模型 (Test) 与名为 tests 的 MySQL 表相关联,其结构如下:

tests
id          int
created_at  date
updated_at  date
correct     boolean

我试图只选择今天、过去 7 天和上个月创建的测试,类似这样(伪代码):

$todays_tests = Test::where('created_at','=', 'today');
$this_weeks_tests = Test::where('created_at','=', 'last 7 days');
$this_months_tests = Test::where('created_at','=', 'last month');

我确信 Laravel 提供了一种简单的方法来做到这一点,但我不确定如何最好地去做。大概我需要使用原始 MySQL 查询?

非常感谢,

【问题讨论】:

    标签: php mysql database laravel laravel-4


    【解决方案1】:

    我相信您可以使用Carbon 插件做一些好事。 Carbon 文档:https://github.com/briannesbitt/Carbon

    例如今天创建的,如果你在你的测试模型中添加这个:

    public function scopeCreatedToday($query)
    {
        return $query->whereBetween('created_at', array(Carbon::today(), Carbon::today()->addDay()));
    }
    

    您将能够做到:$tests = Test::createdToday()->get();

    【讨论】:

    • 这太棒了。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2011-07-14
    • 1970-01-01
    • 1970-01-01
    • 2010-12-25
    • 2011-08-03
    • 2021-03-26
    • 2011-12-02
    • 2020-04-04
    相关资源
    最近更新 更多