对模型的查询和写入操作进行封装

<?php
namespace app\index\model;
use thinkModel;
class User extends Model{
      public function scopeThink($query){
        $query->where('name','think')->field('id,name');
    }
    public function scopeAge($query){
        $query->where('age','>',20)->limit(10);
    }    
}

条件查询:

// 查找name为think的用户
User::scope('think')->find();// 查找年龄大于20的10个用户
User::scope('age')->select();// 查找name为think的用户并且年龄大于20的10个用户
User::scope('think,age')->select();

查询范围的方法可以定义额外的参数
例如User模型类定义如下:

<?php
namespace app\index\model;
use thinkModel;
class User extends Model{
public function scopeEmail($query, $email){
    $query->where('email', 'like', '%' . $email . '%');
    }
    public function scopeScore($query, $score){
    $query->where('score', '>', $score);
    }
    
}

在查询的时候可以如下使用:

// 查询email包含think和分数大于80的用户
User::email('think')->score(80)->select();

使用闭包函数进行查询

User::scope(function($query){
    $query->where('age','>',20)->limit(10);
})->select();

使用查询范围后 只能使用findselect查询。

全局查询范围

所有查询都需要个基础的查询范围 那么可以在模型类里面定义个静态的base方法

use thinkModel;
class User extends Model{// 定义全局的查询范围
protected function base($query){
        $query->where('status',1);
    }
}

然后 执行下面的代码:

$user = User::get(1);

最终的查询条件会是

status = 1 AND id = 1

如果需要动态关闭/开启全局查询访问

// 关闭全局查询范围
User::useGlobalScope(false)->get(1);// 开启全局查询范围
User::useGlobalScope(true)->get(2);