1 回答

TA貢獻(xiàn)1866條經(jīng)驗 獲得超5個贊
TP的模型可以支持原生SQL操作,提供了query和execute兩個方法,為什么原生SQL還要區(qū)分兩個方法呢,原因有兩個:
1、返回類型不同
query用于查詢,返回的是數(shù)據(jù)集,和select或者findall一樣,所以可以直接在模板里面使用volist標(biāo)簽輸出query的查詢結(jié)果
execute用于寫操作,返回的是狀態(tài)或者影響的記錄數(shù)
2、讀寫統(tǒng)計需要
為了便于統(tǒng)計當(dāng)前的數(shù)據(jù)讀寫次數(shù),把數(shù)據(jù)庫的讀和寫操作分開(對應(yīng)的就是query和execute)
?
使用原生SQL很簡單,我們甚至不需要實例化任何的模型,例如:
$Model = new Model(); // 實例化一個空模型
下面的方法是等效的
$Model = D(); 或者 $Model = M();
// 下面執(zhí)行原生SQL操作
$Model->query('select * from think_user where status=1');
$Model->execute('update think_user set status=1 where id=1');
如果你實例化了某個模型,仍然可以執(zhí)行原生SQL操作,不受影響,例如:
$User = D('User');
$User->query('select * from think_user where status=1');
$User->execute('update think_user set status=1 where id=1');
在這種情況下面,我們可以簡化SQL語句的寫法,例如:
$User->query('select * from __TABLE__ where status=1');
$User->execute('update __TABLE__ set status=1 where id=1');
系統(tǒng)會自動把__TABLE__替換成當(dāng)前模型對應(yīng)的數(shù)據(jù)表名稱,實際的數(shù)據(jù)表由模型決定。
- 1 回答
- 0 關(guān)注
- 1113 瀏覽
添加回答
舉報