Laravel  scope用法 
                                                    
                        
                    
                    
  
                    
                    在项目中 经常会面对一些条件的查询,这些查询条件好些是相同的。scope 可以实现这些相同条件的复用.
普通用法:
定义,函数名称为 scope + 首字母大写 LastPost (这个名称随意)
public function scopeWithLastPost($query)
{
    return $query->addSelect([
        'last_post_id' => Post::select(['id'])
            ->whereColumn('user_id', 'users.id')
            ->where('status', Post::STATUS_NORMAL)
            ->orderByDesc('created_at')
            ->limit(1)
    ])->with('lastPost:id,title,user_id,created_at');
}
使用,正常使用,其中调用去掉 scope 后,首字母小写的那个函数。scopeWithLastPost () 调用 withLastPost ()。
$users = User::select($columns)->withLastPost()->orderByDesc('id')->paginate(20);
全局 scope
protected static function boot()
{
    parent::boot(); // TODO: Change the autogenerated stub
    static::addGlobalScope('avaiable',function (Builder $builder){
        $builder->whereIn('status',[0,1]);
    });
}
我们需要重新定义 boot 方法,集成父类 boot 以后,添加全局 scope,这样默认就已经全局使用了。
那么,我们有的时候有的查询是不需要这个全局 scope 的时候怎么办呢?去掉就可以
$posts = Post::withOutGlobalScope('avaiable')->orderBy('created_at','desc')->paginate(10);
本作品采用《CC 协议》,转载必须注明作者和本文链接
          
                    
                    
          
          
                关于 LearnKu
              
                    
                    
                    
 
推荐文章: