- 在模型端创建一个封装的查询或写入方法,方便控制器调用。比如,封装一个筛选所有性别为男的查询,只显示5条部分字段。方法名规范:前缀 scope,后缀随意,调用时直接把后缀作参考组使用;查询范围只能使用find() 和 select() 方法
public function scopeMale($query)
{
$query->where('gender','男')
->field('id,name,gender,email')
->limit(5);
}
public function scope()
{
$result = UserModel::scope('male')->select();
$result = UserModel::male()->select();
}
- 查询封装可以传递参数
public function scopeEmail($query,$value)
{
$query->where('email','like','%'.$value.'%');
}
$result = UserModel::scope('email','xiao')->select();
$result = UserModel::email('xiao')->select();
- 多个查询方法连缀调用,比如找出邮箱xiao 并大于80分的
public function scopePrice($query,$value)
{
$query->where('price','>',$value);
}
public function scopeEmail($query,$value)
{
$query->where('email','like','%'.$value.'%');
}
$result = UserModle::scope('email','xiao')->scope('price','90')->select();
$result = UserModel::email('xiao')->price(90)->select();
- 全局范围查询,在此模型下不管怎么查询都会加全局条件
protected $globalscope =['status'];
public function scopeStatus($query)
{
$query->where('status',1);
}
UserModel::withoutGlobalScope();
UserModel::withoutGlobalScope(['status']);