tp5 model 中的查询范围(scope)


查询范围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);
    }

}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM