寫在模型中且轨,供模型調(diào)用(和關(guān)聯(lián)查詢類似),來判斷是否有沒有這個范圍
一虚婿、語法
public function scopeActive(Builder $query, 參數(shù)){
return $query->where('active', 1);
}
public function articleTopics(){
return $this->hasMany('App\Http\Model\ArticleTopic','article_id','id');
}
doesntHave中第一個參數(shù)為關(guān)聯(lián)模型
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,第二個參數(shù)可以根據(jù)需要定義然痊。
返回值也必須是Builder
二至朗、用法:
$user = App\User::popular()->active()->orderBy('created_ar')->get();
三、全局scope
同樣在模型里面編寫,對當(dāng)前模型生效剧浸;
//全局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);