寫在模型中,供模型調用(和關聯查詢類似),來判斷是否有沒有這個范圍
一、語法
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);