查询范围
对于一些常用的查询条件,我们可以封装成查询范围来进行方便的调用。
例如,邮箱地址为thinkphp@qq.com和status为1这两个常用查询条件,可以定义为模型类的两个查询范围方法
模型配置
//查寻范围、email查寻
//查询范围 把经常需要查询的地方 放在一个模式的方法里面,以后每次需要用的时候调用一下这个方法就可以了。
//方法命名规范 scope+查询范围名称
//查寻范围、email查寻
//查询范围 把经常需要查询的地方 放在一个模式的方法里面,以后每次需要用的时候调用一下这个方法就可以了。
//方法命名规范 scope+查询范围名称
protected function scopeEmail($query) // ,$query 查询对像
{
$query->where('email', 'tpshop@tpshop.cn'); //查询参数
//$query->where('email', $e);
}
控制器
$list = Users::scope('email','wanggang@qq.com')->select();//传参数方式
//SELECT * FROM `tp_users` WHERE `email` = 'tpshop@tpshop.cn'
users模型
protected function scopeEmail($query) // ,$query 查询对像
{
$query->where('email', 'tpshop@tpshop.cn'); //查询参数
//$query->where('email', $e);
}
//查询用户等级
protected function scopeLevel($query){
$query->where('level',1);
}
控制器 ,同里调用两个方法
$list = Users::scope('email,level')->select();
//SELECT * FROM `tp_users` WHERE `email` = 'tpshop@tpshop.cn' AND `level` = 1
user模型传参方式
protected function scopeEmail($query,$a) // ,$query 查询对像
{
$query->where('email', $a);
}
控制器及结果
$list = Users::scope('email','wanggang@qq.com')->select();//传参数方式
//SELECT * FROM `tp_users` WHERE `email` = 'wanggang@qq.com'
多个查询范围联合使用
//多个查询范围联合使用
$list = Users::scope('email')
->scope('level')
->scope(function($query){
$query->order('user_id','desc');
})
->all();
全局查询范围 所有该模型下的查询where条件都会加上 user_id = 1;
//全局查询范围
protected static function base($query){
$query->where('user_id',1);
}
在控制器里面使用
$list = Users::scope('email,level')->select();
//SELECT * FROM `tp_users` WHERE `user_id` = 1 AND `email` = 'tpshop@tpshop.cn' AND `level` = 1
他默认的都会把所有的 USER_ID = 1 添加进去。