Laravel检索模型的全局范围

时间:2014-10-14 23:23:52

标签: php laravel laravel-4 eloquent

我正从数据库中检索Events,每次从数据库中获取事件时,我都要检查where active_from <= today

如何定义在检索模型时使用的全局范围?

2 个答案:

答案 0 :(得分:0)

您需要创建一个像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
    }
}

答案 1 :(得分:0)

您可以将全局范围(例如: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());
    })

}
相关问题