查詢范圍

可以對模型的查詢和寫入操作進行封裝,例如:

namespace app\index\model;

use think\Model;

class User extends Model
{

    protected function scopeThinkphp($query)
    {
        $query->where('name','thinkphp')->field('id,name');
    }
    
    protected function scopeAge($query)
    {
        $query->where('age','>',20)->limit(10);
    }    
    
}

就可以進行下面的條件查詢:

// 查找name為thinkphp的用戶
User::scope('thinkphp')->find();
// 查找年齡大于20的10個用戶
User::scope('age')->select();
// 查找name為thinkphp的用戶并且年齡大于20的10個用戶
User::scope('thinkphp,age')->select();

可以直接使用閉包函數(shù)進行查詢,例如:

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

參數(shù)支持:

namespace app\index\model;

use think\Model;

class User extends Model
{

    protected function scopeAgeAbove($query, $lowest_age)
    {
        $query->where('age','>',$lowest_age)->limit(10);
    }    
}

User::scope('ageAbove', 20)->select();

scope 的name 駝峰的 只能 ageAbove AgeAbove 不支持 age_above

支持動態(tài)調(diào)用的方式,例如:

$user = new User;
// 查找name為thinkphp的用戶
$user->thinkphp()->get();
// 查找年齡大于20的10個用戶
$user->age()->all();
// 查找name為thinkphp的用戶并且年齡大于20的10個用戶
$user->thinkphp()->age()->all();

命名范圍方法之前不能調(diào)用查詢的連貫操作方法,必須首先被調(diào)用。如果在查詢范圍方法后面調(diào)用了其他的鏈式查詢方法,則只能使用find或者select查詢。

全局查詢范圍

如果你的所有查詢都需要一個基礎(chǔ)的查詢范圍,那么可以在模型類里面定義一個靜態(tài)的base方法,例如:

namespace app\index\model;

use think\Model;

class User extends Model
{
    // 定義全局的查詢范圍
    protected function base($query)
    {
        $query->where('status',1);
    }
}

全局查詢范圍方法在5.0.2版本之前必須定義為static靜態(tài)方法。

然后,執(zhí)行下面的代碼:

$user = User::get(1);

最終的查詢條件會是

status = 1 AND id = 1

如果需要動態(tài)關(guān)閉/開啟全局查詢訪問,可以使用:

// 關(guān)閉全局查詢范圍
User::useGlobalScope(false)->get(1);
// 開啟全局查詢范圍
User::useGlobalScope(true)->get(2);
文檔最后更新時間:2018-04-26 10:07:48

文檔
目錄

深色
模式

切換
寬度