Thinkphp5.0 的使用模型Model更新數據
(1)使用update()方法進行更新數據
一、where條件寫在更新數據中
(這種情況更新的數據,必須含主鍵)
$res = User::update([ 'id' => 2, 'email' => '121@qq.com' ]); //返回修改之后model的整個對象信息 dump($res);
二、where條件使用update()的第二個參數,傳遞數組
$res = User::update([ 'email' => '123@qq.com' ],['id'=>2]); //返回修改之后model的整個對象信息 dump($res);
三、where條件使用update()的第二個參數,傳遞閉包函數
$res = User::update([ 'email' => '555@qq.com' ],function($query){ $query->where(['id'=>2]); }); //返回修改之后model的整個對象信息 dump($res);
四、使用where條件
$res = User::where('id','=',2)->update([ 'email'=>'666@qq.com' ]); //返回影響的行數 dump($res);
(2)使用save()方法
方式一:
$model = User::get(2); $model->email = '777@qq.com'; $res = $model->save(); //返回影響的行數 dump($res);
方式二:
$model = new User(); $res2 = $model->save([ 'email' => '999@qq.com' ],['id'=>2]); //返回影響的行數 dump($res2);
方式三:
$model = new User(); $res = $model->save([ 'email' => '000@qq.com' ],function($query){ $query->where(['id'=>2]); }); //返回影響的行數 dump($res);
使用saveAll()方法更新多個數據:
$model = new User(); $res = $model->saveAll([ ['id' => 2,'email' => '122@qq.com'], ['id' => 3,'email' => '123@qq.com'], ['id' => 4,'email' => '124@qq.com'] ]); //返回數組 dump($res);