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