laravel 中scope 应用

在模型中定义

protected static function boot() {
Model::boot();

static::addGlobalScope('defaultOrder', function (Builder $builder) {
$builder->orderBy('id', 'desc');
});

static::addGlobalScope('top_level', function (Builder $builder) {
$builder->where('reply_to', null);
});
}

 

如上所示,设置了默认的排序 及增加查询条件

然而 要注意的是,在查询中,当不需要scope的时侯,需要加上

比如删除时 需要加上调用静态方法 withoutGlobalScope

$id = request("id");
Model::withoutGlobalScope('top_level')->where('id', $id)

  

 

posted on 2019-03-15 17:06  lianruihong  阅读(323)  评论(0编辑  收藏  举报

导航