更新
版本 | 調(diào)整功能 |
---|---|
5.0.13 |
saveAll 方法支持isUpdate 方法強制更新 |
5.0.10 |
模型增加setInc 和setDec 方法 |
查找并更新
在取出數(shù)據(jù)后,更改字段內(nèi)容后更新數(shù)據(jù)。
$user = User::get(1);
$user->name = 'thinkphp';
$user->email = 'thinkphp@qq.com';
$user->save();
直接更新數(shù)據(jù)
也可以直接帶更新條件來更新數(shù)據(jù)
$user = new User;
// save方法第二個參數(shù)為更新條件
$user->save([
'name' => 'thinkphp',
'email' => 'thinkphp@qq.com'
],['id' => 1]);
上面兩種方式更新數(shù)據(jù),如果需要過濾非數(shù)據(jù)表字段的數(shù)據(jù),可以使用:
$user = new User();
// 過濾post數(shù)組中的非數(shù)據(jù)表字段數(shù)據(jù)
$user->allowField(true)->save($_POST,['id' => 1]);
如果你通過外部提交賦值給模型,并且希望指定某些字段寫入,可以使用:
$user = new User();
// post數(shù)組中只有name和email字段會寫入
$user->allowField(['name','email'])->save($_POST, ['id' => 1]);
批量更新數(shù)據(jù)
可以使用saveAll方法批量更新數(shù)據(jù),例如:
$user = new User;
$list = [
['id'=>1, 'name'=>'thinkphp', 'email'=>'thinkphp@qq.com'],
['id'=>2, 'name'=>'onethink', 'email'=>'onethink@qq.com']
];
$user->saveAll($list);
批量更新僅能根據(jù)主鍵值進行更新,其它情況請使用
foreach
遍歷更新。
V5.0.13+
版本開始,你可以使用下面的方式強制進行數(shù)據(jù)更新操作而不是新增操作(尤其適合于復合主鍵的情況)。
$user = new User;
$list = [
['id'=>1, 'name'=>'thinkphp', 'email'=>'thinkphp@qq.com'],
['id'=>2, 'name'=>'onethink', 'email'=>'onethink@qq.com']
];
$user->isUpdate()->saveAll($list);
通過數(shù)據(jù)庫類更新數(shù)據(jù)
必要的時候,你也可以使用數(shù)據(jù)庫對象來直接更新數(shù)據(jù),但這樣就無法使用模型的事件功能。
$user = new User;
$user->where('id', 1)
->update(['name' => 'thinkphp']);
或者使用:
$user = new User;
$user->update(['id' => 1, 'name' => 'thinkphp']);
如果傳入
update
的數(shù)據(jù)包含主鍵的話,可以無需使用where
方法。
靜態(tài)方法
模型支持靜態(tài)方法直接更新數(shù)據(jù),例如:
User::where('id', 1)
->update(['name' => 'thinkphp']);
或者使用:
User::update(['id' => 1, 'name' => 'thinkphp']);
閉包更新
可以通過閉包函數(shù)使用更復雜的更新條件,例如:
$user = new User;
$user->save(['name' => 'thinkphp'],function($query){
// 更新status值為1 并且id大于10的數(shù)據(jù)
$query->where('status', 1)->where('id', '>', 10);
});
自動識別
我們已經(jīng)看到,模型的新增和更新方法都是save
方法,系統(tǒng)有一套默認的規(guī)則來識別當前的數(shù)據(jù)需要更新還是新增。
- 實例化模型后調(diào)用save方法表示新增;
- 查詢數(shù)據(jù)后調(diào)用save方法表示更新;
- save方法傳入更新條件后表示更新;
如果你的數(shù)據(jù)操作比較復雜,可以顯式的指定當前調(diào)用save
方法是新增操作還是更新操作。
顯式更新數(shù)據(jù):
// 實例化模型
$user = new User;
// 顯式指定更新數(shù)據(jù)操作
$user->isUpdate(true)
->save(['id' => 1, 'name' => 'thinkphp']);
顯式新增數(shù)據(jù):
$user = User::get(1);
$user->name = 'thinkphp';
// 顯式指定當前操作為新增操作
$user->isUpdate(false)->save();
注意不要在一個模型實例里面做多次更新,會導致部分重復數(shù)據(jù)不再更新,正確的方式應該是先查詢后更新或者使用模型類的update
方法更新。
如果你調(diào)用save方法進行多次數(shù)據(jù)寫入的時候,需要注意,第二次save方法的時候必須使用isUpdate(false),否則會視為更新數(shù)據(jù)。