zoukankan      html  css  js  c++  java
  • tp5 model 中的查询范围(scope)

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

    namespace appindexmodel;
    
    use thinkModel;
    
    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 appindexmodel;
    
    use thinkModel;
    
    class User extends Model
    {
       // 所有的查询都会自动添加查询条件 status = 1  
        protected static function base($query){   // 5.0.2版本之前需要使用static定义
            $query -> where('status',1);
        }
    
    }
  • 相关阅读:
    OnContextMenu事件
    wireshark教程
    常见的算法题:逆行单一列表
    GPIO
    USB OTG简要
    软测验点---平衡二叉树
    SSL工作原理
    CFileDialog 使用简单介绍
    eclipse在maven项目交付svn忽略简介
    四个漂亮CSS样式表
  • 原文地址:https://www.cnblogs.com/chrdai/p/6144426.html
Copyright © 2011-2022 走看看