1. 程式人生 > >ThinkPHP5.0 模型更新操作

ThinkPHP5.0 模型更新操作

for 庫類 each name where div blog list 實例

1、在取出數據後,更改字段內容後更新數據

$user = User::get(1);
$user->name     = ‘thinkphp;
$user->email    = ‘[email protected];
$user->save();

2、直接帶更新條件來更新數據

$user = new User;
// save方法第二個參數為更新條件
$user->save([
    ‘name‘  => ‘thinkphp‘,
    ‘email‘ => [email protected]
],[‘id‘ => 1]);

3、過濾非數據表字段的數據

$user = new User();
// 過濾post數組中的非數據表字段數據
$user->allowField(true)->save($_POST,[‘id‘ => 1]);

4、通過外部提交賦值給模型,並且希望指定某些字段寫入

$user = new User();
// post數組中只有name和email字段會寫入
$user->allowField([‘name‘,‘email‘])->save($_POST, [‘id‘ => 1]);

5、saveAll方法批量更新數據

$user = new User;
$list = [ [‘id‘=>1, ‘name‘=>‘thinkphp‘, ‘email‘=>[email protected]], [‘id‘=>2, ‘name‘=>‘onethink‘, ‘email‘=>[email protected]] ]; $user->saveAll($list);

7、通過遍歷批量更新數據

$user = new User;
$list = [
    [‘id‘=>1, ‘name‘=>‘thinkphp‘, ‘email‘=>[email protected]
/* */], [‘id‘=>2, ‘name‘=>‘onethink‘, ‘email‘=>[email protected]] ]; foreach($list as $data){ $user->data($data,true)->isUpdate(true)->save(); }

8、通過數據庫類更新數據(兩種形式)

$user = new User;
$user->where(‘id‘, 1)
    ->update([‘name‘ => ‘thinkphp‘]);


$user = new User;
$user->update([‘id‘ => 1, ‘name‘ => ‘thinkphp‘]);

9、靜態方法直接更新數據(兩種形式)

//第一種形式
User::where(‘id‘, 1) ->update([‘name‘ => ‘thinkphp‘]);

//第二種形式
User::update([‘id‘ => 1, ‘name‘ => ‘thinkphp‘]);

10、閉包函數使用更復雜的更新條件

$user = new User;
$user->save([‘name‘ => ‘thinkphp‘],function($query){
    // 更新status值為1 並且id大於10的數據
    $query->where(‘status‘, 1)->where(‘id‘, ‘>‘, 10);
});

11、自動識別主鍵更新

// 實例化模型
$user = new User;
// 顯式指定更新數據操作
$user->isUpdate(true)->save([‘id‘ => 1, ‘name‘ => ‘thinkphp‘]);

ThinkPHP5.0 模型更新操作