【问题标题】:Laravel global scope on retrieving a modelLaravel 检索模型的全局范围
【发布时间】:2014-10-14 23:23:51
【问题描述】:

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

我如何定义一个全局范围,当我检索模型时将使用它?

【问题讨论】:

标签: php laravel laravel-4 eloquent


【解决方案1】:

您需要创建一个像 EventsTrait 这样的特征,并在该特征内添加一个 bootEventTrait 函数,该函数将添加一个像 EventsScope 这样的全局范围。使用 SoftDeletingTrait 作为模式。

事件特征

trait EventsTrait {

    public static function bootEventsTrait()
    {
        static::addGlobalScope(new EventsScope);
    }

}

事件范围

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
    }
}

【讨论】:

    【解决方案2】:

    您可以向 Event 模型添加全局范围(例如: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());
        })
    
    }
    

    【讨论】:

      猜你喜欢
      • 2023-03-09
      • 2016-04-14
      • 2015-12-02
      • 1970-01-01
      • 2015-07-06
      • 2015-12-06
      • 1970-01-01
      • 2016-05-29
      • 2019-06-22
      相关资源
      最近更新 更多