寫在模型中,供模型調(diào)用(和關(guān)聯(lián)查詢類似),來判斷是否有沒有這個(gè)范圍
一、語法
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中第一個(gè)參數(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開頭。后面第一個(gè)字母大寫。
后面括號(hào)中第一個(gè)必須是Builder,第二個(gè)參數(shù)可以根據(jù)需要定義。
返回值也必須是Builder
二、用法:
$user = App\User::popular()->active()->orderBy('created_ar')->get();
三、全局scope
同樣在模型里面編寫,對(duì)當(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);