查詢范圍
可以對模型的(de)查詢和寫入操作進(jin)行封裝(zhuang),例如:
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);
}
}
就可以進行下面的(de)條件(jian)查詢:
// 查找name為thinkphp的(de)用戶
User::scope('thinkphp')->find();
// 查找(zhao)年齡大于(yu)20的10個用(yong)戶
User::scope('age')->select();
// 查(cha)找name為thinkphp的(de)用戶并且(qie)年齡(ling)大于20的(de)10個用戶
User::scope('thinkphp,age')->select();
可以直(zhi)接使用閉包函數進行查詢,例如:
User::scope(function($query){
$query->where('age','>',20)->limit(10);
})->select();
參數支持:
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 不支(zhi)持 age_above
支持動態調用的方式(shi),例如:
$user = new User;
// 查找name為thinkphp的用戶
$user->thinkphp()->get();
// 查找年齡大于20的10個用戶
$user->age()->all();
// 查找name為thinkphp的用戶并且年齡大于20的10個用戶
$user->thinkphp()->age()->all();
命名范圍方(fang)(fang)法之前不(bu)能調(diao)用(yong)(yong)查(cha)詢的連貫操(cao)作方(fang)(fang)法,必須首先被調(diao)用(yong)(yong)。如果在查(cha)詢范圍方(fang)(fang)法后(hou)面調(diao)用(yong)(yong)了(le)其他的鏈式查(cha)詢方(fang)(fang)法,則只能使用(yong)(yong)find或者select查(cha)詢。
全局查詢范圍
如果你的所有查詢都需要一個基礎的查詢范圍,那么可以在模型類里面定義一個靜態的base方法,例如:
namespace app\index\model;
use think\Model;
class User extends Model
{
// 定義(yi)全局的查詢(xun)范圍
protected function base($query)
{
$query->where('status',1);
}
}
全局查詢范圍方法在5.0.2版本之前必須定義為
static靜態方法。
然(ran)后,執行下面的代碼:
$user = User::get(1);
最終的查詢條件(jian)會是
status = 1 AND id = 1
如果需要動(dong)態關閉/開啟全局查詢訪(fang)問,可以使用:
// 關閉全局查詢范(fan)圍
User::useGlobalScope(false)->get(1);
// 開(kai)啟全局查詢范(fan)圍
User::useGlobalScope(true)->get(2);
文檔最后更新時間:2018-04-26 10:07:48
未解決你的問題?請到「問答社區」反饋你遇到的問題
