我从数据库中每一次我得到我要检查Events
数据库事件时间检索where active_from <= today
。
我怎么能定义一个全球范围内,当我恢复模型将被使用?
你需要创建一个像EventsTrait的性状和特征内,加一个bootEventTrait功能,将增加像EventsScope全局范围。使用SoftDeletingTrait的模式。
EventTrait
trait EventsTrait {
public static function bootEventsTrait()
{
static::addGlobalScope(new EventsScope);
}
}
EventScope
use Illuminate\Database\Eloquent\ScopeInterface;
use Illuminate\Database\Eloquent\Builder;
class EventScope implements ScopeInterface {
public function apply(Builder $builder)
{
$builder->where("active_from","<=", "today");
}
public function remove(Builder $builder)
{
// remove scope
}
}
您可以在全球范围内增加(如:IS_ACTIVE)的事件模型。
// App\Event.php
use Carbon\Carbon;
public static function boot(){
parent::boot();
static::addGlobalScope('is_active', function($builder){
$builder->where('active_from', '<=', Carbon::now());
})
}