tp5 model 中的查询范围(scope)

时间:2022-02-13 02:55:36

查询范围scope在model中定义,在controller中使用

namespace app\index\model;

use think\Model;

class User extends Model
{
// 查询条件为 name = 'thinkphp' ,且只查询 id 和 name两个字段
protected function scopeThinkphp($query)
{
$query->where('name','thinkphp')->field('id,name');
}

// 查询条件为 score > 80
protected function scopeAge($query)
{
$query->where('score','>',80);
}

}

controller中任然可以写组合查询代码

    public function index(Request $request)
{
$user = model('User');
$data = $user::scope('thinkphp,score')->where('status',1)->paginate(5); // 查询name = 'thinkphp',score>80且status = 1 并且只查询 id 和 name 两个字段的数据
$this-> assign('data',$data);
return $this->fetch(); // 渲染到模板后跟Db查询方法一样使用
}

使用base方法定义全局查询范围

namespace app\index\model;

use think\Model;

class User extends Model
{
// 所有的查询都会自动添加查询条件 status = 1
protected static function base($query){ // 5.0.2版本之前需要使用static定义
$query -> where('status',1);
}

}