在检索模型Laravel全球范围内

问题描述 投票:0回答:2

我从数据库中每一次我得到我要检查Events数据库事件时间检索where active_from <= today

我怎么能定义一个全球范围内,当我恢复模型将被使用?

php laravel laravel-4 eloquent
2个回答
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
    }
}

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());
    })

}
© www.soinside.com 2019 - 2024. All rights reserved.