global scopes
1编写 2应用 3匿名 4移除
1.编写
定义一个实现 Illuminate\Database\Eloquent\Scope 接口的类,该接口要求你实现一个方法:apply。需要的话可以在 apply 方法中添加 where 条件到查询:
如 <code>return $builder->where('age',>,200);</code>
2 应用
需要重写给定模型的 boot 方法并使用 addGlobalScope 方法
AgeScope就是编写的类
<code>static::addGlobalScope(new AgeScope);</code>
添加作用域后,如果使用 User::all() 查询则会生成如下SQL语句:
<code>select * fromusers
whereage
> 200</code>
3 匿名
意思是无需编写新建一个实现Scope接口的类,而是以匿名函数的方式实现
<code>
static::addGlobalScope('age', function(Builder $builder) {
$builder->where('age', '>', 200);
});
</code>
利用 age 标识符来移除全局作用
<code>User::withoutGlobalScope('age')->get();</code>
4移除
查询时加上withoutGlobalScope或者withoutGlobalScopes
对应单个或者多个查询作用域
local scopes
在模型中定义方法以scope开头,如scopeActive()
在查询的时候我们可以这样写:
<code>User::active()->all()</code>
我们也可以提供参数查询
我们scopeOftype($query,$type)里的$type就是一个动态参数