欢迎光临
我们一直在努力

Laravel模型的scope过滤

写在模型中,供模型调用(和关联查询类似),来判断是否有没有这个范围

一、语法

public function scopeActive(Builder $query,  参数){
  return $query->where('active', 1);
}

public function articleTopics(){
        return $this->hasMany('App\Http\Model\ArticleTopic','article_id','id');
}
doesntHave中第一个参数为关联模型
public function scopeTopicNotBy(Builder $query, $topic_id){
        return $query->doesntHave('articleTopics','and', function($q)use($topic_id){
            $q->where('topic_id', $topic_id);
        });
 }

解析:
必须以scope开头。后面第一个字母大写。
后面括号中第一个必须是Builder,第二个参数可以根据需要定义。
返回值也必须是Builder

二、用法:

$user = App\User::popular()->active()->orderBy('created_ar')->get();

三、全局scope

同样在模型里面编写,对当前模型生效;

//全局scope
    protected static function boot(){
        parent::boot();
        static::addGlobalScope('avaiable',function(Builder $builder){
            $builder->whereIn('status',[0,1]);
        });
    }

四、如何取消全局scope

有的地方我们用不到这全局scope,需要排除在外
带上withoutGlobalScope即可

Article::withoutGlobalScope('avaiable')->where('status', 0)->orderBy('created_at','desc')->paginate(10);
赞(1)
版权归原作者所有,如有侵权请告知。达维营-前端网 » Laravel模型的scope过滤

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址