Lumen - 从所有 select 方法中过滤一些结果
Lumen - Filter some results from all select methods
我在数据库中有一个 expired_at
列;在创建任何行时,默认情况下将是创建时间的未来 5 分钟,我想排除它们的 expired_at
已经过去的行(从当前时间开始比较少)。
例如,我在 games
table 中有以下行:
id creator_id created_at updated_at expire_at
1 123456789 2017-04-26 01:13:22 2017-04-26 01:13:22 2017-04-26 01:18:22
2 234567890 2017-04-26 01:16:06 2017-04-26 01:16:06 2017-04-26 01:21:06
并且当我在 01:19:30
时使用 Game::all()
或 Game::where('condition')
函数获取所有行时,不应该获取第 1 行,但应该获取第 2 行,因为它还没有过期.
我不想在目标代码中处理过期时间,而是在模型代码中(例如覆盖模型中的 where 函数 class)
您可以通过(全局)作用域实现这一点。
另见 this link。
protected static function boot()
{
parent::boot();
static::addGlobalScope('not_expired', function (Builder $builder) {
$builder->where('expired_at', '>', Carbon::now());
});
}
全局范围将应用于所有查询,除非您专门禁用它们。
可以通过以下方式禁用它们:
Game::withoutGlobalScope('not_expired')->all();
我在数据库中有一个 expired_at
列;在创建任何行时,默认情况下将是创建时间的未来 5 分钟,我想排除它们的 expired_at
已经过去的行(从当前时间开始比较少)。
例如,我在 games
table 中有以下行:
id creator_id created_at updated_at expire_at
1 123456789 2017-04-26 01:13:22 2017-04-26 01:13:22 2017-04-26 01:18:22
2 234567890 2017-04-26 01:16:06 2017-04-26 01:16:06 2017-04-26 01:21:06
并且当我在 01:19:30
时使用 Game::all()
或 Game::where('condition')
函数获取所有行时,不应该获取第 1 行,但应该获取第 2 行,因为它还没有过期.
我不想在目标代码中处理过期时间,而是在模型代码中(例如覆盖模型中的 where 函数 class)
您可以通过(全局)作用域实现这一点。
另见 this link。
protected static function boot()
{
parent::boot();
static::addGlobalScope('not_expired', function (Builder $builder) {
$builder->where('expired_at', '>', Carbon::now());
});
}
全局范围将应用于所有查询,除非您专门禁用它们。
可以通过以下方式禁用它们:
Game::withoutGlobalScope('not_expired')->all();