一、模型查询范围
1、在模型端创建一个封装的查询或写入方法,方便控制器端等调用
2、封装一个筛选出权限为1的查询,并且只显示部分字段5条
3、方法名规范:前缀scope,后缀随意,调用时直接把后缀作为参数使用
public function scopeMale($query)
{
$query->where('type','1')
->field('id','uname','upass')
->limit(5);
}
4、在控制器端直接调用并输出结果
public function scope()
{
$result=Students::scope('type')->select();
//$result=Students::male()->select();
return json($result);
}
5、查询封装可以传递参数,比如,通过有邮箱查找某人
//模型端
public function scopeEmail($query,$value)
{
$query->where('email','like','%'.$value.'%')
}
//控制器端
$result=Students::scope('email','xiao')->select();
$result=Students::email('xiao')->select();
return json($result);
6、也可以实现多个查询封装方法连缀调用,比如找出邮箱xiao并大于80的
//模型端
public function scopePrice($query,$value)
{
$query->where('price','>',$value);
}
//控制器端
$result=Students::scope('email','xiao')
->scope('price',80)
->select();
return json($result);
7、查询范围只能使用find()和select()两种方法
8、全局范围查询,就是在此模型下不管怎么查询都会加上全局条件
//全局范围 //模型端
protected $globalScope=['status'];
//全局范围 //控制器端
public function scopeStatus($query)
{
$querty->where('status',1);
}
9、在定义了全局查询后,如果向取消这个查询的所有全局查询,可以用下面的方法
Students::withoutGlobalScope()
10、在定义了全局查询后,如果向取消这个查询的部分全局查询,可以添加指定参数
Students::withoutGlobalScope(['status']);