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