## 更新數據
可以使用save方法更新數據
~~~
Db::name('user')
->save(['id' => 1, 'name' => 'thinkphp']);
~~~
或者使用`update`方法。
~~~
Db::name('user')
->where('id', 1)
->update(['name' => 'thinkphp']);
~~~
`update`方法返回影響數據的條數,沒修改任何數據返回 0
~~~
// 支持使用`data`方法傳入要更新的數據
Db::name('user')
->where('id', 1)
->data(['name' => 'thinkphp'])
->update();
~~~
如果`update`方法和`data`方法同時傳入更新數據,則以`update`方法為準。
~~~
//如果數據中包含主鍵,可以直接使用:
Db::name('user')
->update(['name' => 'thinkphp','id' => 1]);
~~~
如果要更新的數據需要使用`SQL`函數或者其它字段,可以使用下面的方式:
~~~
Db::name('user')
->where('id',1)
->exp('name','UPPER(name)')
->update();
~~~
支持使用`raw`方法進行數據更新。
~~~
Db::name('user')
->where('id', 1)
->update([
'name' => Db::raw('UPPER(name)'),
'score' => Db::raw('score-3'),
'read_time' => Db::raw('read_time+1')
]);
~~~
## 自增自減
`inc/dec`方法自增或自減一個字段的值( 如不加第二個參數,默認步長為1)。
~~~
// score 字段加 1
Db::table('think_user')
->where('id', 1)
->inc('score')
->update();
// score 字段加 5
Db::table('think_user')
->where('id', 1)
->inc('score', 5)
->update();
// score 字段減 1
Db::table('think_user')
->where('id', 1)
->dec('score')
->update();
// score 字段減 5
Db::table('think_user')
->where('id', 1)
->dec('score', 5)
->update();
~~~