可以对模型的查询和写入操作进行封装,例如:
namespace app\index\model;use think\Model;class User extends Model{ protected function scopeThinkphp($query) { $query->where('name','thinkphp')->field('id,name'); } protected function scopeAge($query) { $query->where('age','>',20)->limit(10); } }
就可以进行下面的条件查询:
// 查找name为thinkphp的用户User::scope('thinkphp')->find();// 查找年龄大于20的10个用户User::scope('age')->select();// 查找name为thinkphp的用户并且年龄大于20的10个用户User::scope('thinkphp,age')->select();
可以直接使用闭包函数进行查询,例如:
User::scope(function($query){ $query->where('age','>',20)->limit(10); })->select();
参数支持:
namespace app\index\model;use think\Model;class User extends Model{ protected function scopeAgeAbove($query, $lowest_age) { $query->where('age','>',$lowest_age)->limit(10); } } User::scope('ageAbove', 20)->select();
scope 的name 驼峰的 只能 ageAbove AgeAbove 不支持 age_above
支持动态调用的方式,例如:
$user = new User;// 查找name为thinkphp的用户$user->thinkphp()->get();// 查找年龄大于20的10个用户$user->age()->all();// 查找name为thinkphp的用户并且年龄大于20的10个用户$user->thinkphp()->age()->all();
命名范围方法之前不能调用查询的连贯操作方法,必须首先被调用。如果在查询范围方法后面调用了其他的链式查询方法,则只能使用find或者select查询。
如果你的所有查询都需要一个基础的查询范围,那么可以在模型类里面定义一个静态的base
方法,例如:
namespace app\index\model;use think\Model;class User extends Model{ // 定义全局的查询范围 protected function base($query) { $query->where('status',1); } }
全局查询范围方法在5.0.2版本之前必须定义为
static
静态方法。
然后,执行下面的代码:
$user = User::get(1);
最终的查询条件会是
status = 1 AND id = 1
如果需要动态关闭/开启全局查询访问,可以使用:
// 关闭全局查询范围User::useGlobalScope(false)->get(1);// 开启全局查询范围User::useGlobalScope(true)->get(2);