tp5 中 model 的更新方法
// 过滤非数据表字段更新 public function update(Request $request){ $user = model('User'); $result = $user -> allowField(true)->save($request->param(),['id'=>1]); dump($result); // 受影响的行数 }
//更新指定字段 public function update(Request $request){ $user = model('User'); $result = $user -> allowField(['name','email'])->save($request->param(),['id'=>9]); dump($result); }
数据库类更新数据(推荐)
public function update(Request $request){ $user = model('User'); $user->where('id',1) ->update(['name'=>'chrdai']); }
闭包更新数据(更新条件为多个时,推荐)
public function update(Request $request){ $user = model('User'); $user->save(['name'=>'chrdai'],function($query){ $query->where('status',1)->where('id','>',18); }); }
静态方法更新数据
public function update(Request $request){ $user = model('User'); $user::where('id',1) ->update(['name'=>'chrdai','email'=>'chrdai@qq.com']); }
批量更新数据saveAll()
$user =model('User'); $list = [ ['id'=>1, 'name'=>'thinkphp', 'email'=>'thinkphp@qq.com'], ['id'=>2, 'name'=>'onethink', 'email'=>'onethink@qq.com'] ]; $user->saveAll($list);