You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel Eloquent查询:添加start_time晚于当前时间的条件方法

嘿,这个需求挺实用的,我给你两种靠谱的实现方式,让你能轻松用上whereAfterNow这种简洁的查询方法:

方法一:在模型基类中添加静态方法

如果只是想让自己的业务模型支持这个方法,最简单的方式是在你的模型基类(通常是app/Models/Model.php,所有业务模型都继承它)里添加一个静态方法:

namespace App\Models;

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

class Model extends BaseModel
{
    // 这里是你原本的基类代码...

    /**
     * 添加查询条件:指定字段晚于当前时间
     * @param string $column 要判断的字段名
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public static function whereAfterNow($column)
    {
        return static::where($column, '>', Carbon::now());
    }
}

这样,任何继承这个基类的模型都可以直接调用:

// 注意:别用all(),它会忽略之前的查询条件!要用get()/first()/paginate()等
YourModel::whereAfterNow('start_time')->get();
方法二:全局查询宏(所有查询构建器可用)

如果想让所有查询场景都支持这个方法(包括直接用DB门面操作表),可以在服务提供者里注册一个查询宏:

打开app/Providers/AppServiceProvider.php,在boot方法里添加代码:

namespace App\Providers;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Carbon;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function register()
    {
        // 原本的注册代码...
    }

    public function boot()
    {
        // 注册whereAfterNow宏
        Builder::macro('whereAfterNow', function ($column) {
            return $this->where($column, '>', Carbon::now());
        });
    }
}

这下不管是模型还是DB门面都能调用:

// 模型调用
YourModel::whereAfterNow('start_time')->get();

// DB门面直接操作表
DB::table('events')->whereAfterNow('start_time')->get();
几个注意点
  • 时区问题:Carbon::now()会使用你在config/app.php里配置的timezone,如果需要用UTC时间,换成Carbon::utcNow()即可。
  • 别用all():你例子里的Model::whereAfterNow('start_time')->all()是无效的,因为all()是模型的静态方法,会直接返回所有记录,不会应用之前的查询条件。一定要用get()、first()这类查询构建器的方法。

内容的提问来源于stack exchange,提问作者Davit Zeynalyan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:20:48