更新數(shù)據(jù)
版本 | 調(diào)整功能 |
---|---|
5.0.5 |
添加data /inc /dec /exp 方法設(shè)置數(shù)據(jù) |
更新數(shù)據(jù)表中的數(shù)據(jù)
Db::table('think_user')->where('id', 1)->update(['name' => 'thinkphp']);
如果數(shù)據(jù)中包含主鍵,可以直接使用:
Db::table('think_user')->update(['name' => 'thinkphp','id'=>1]);
update 方法返回影響數(shù)據(jù)的條數(shù),沒(méi)修改任何數(shù)據(jù)返回 0
如果要更新的數(shù)據(jù)需要使用SQL
函數(shù)或者其它字段,可以使用下面的方式:
Db::table('think_user')
->where('id', 1)
->update([
'login_time' => ['exp','now()'],
'login_times' => ['exp','login_times+1'],
]);
V5.0.18+
版本開(kāi)始是數(shù)組中使用exp
查詢(xún)和更新的話(huà),必須改成下面的方式:
Db::table('think_user')
->where('id', 1)
->update([
'login_time' => Db::raw('now()'),
'login_times' => Db::raw('login_times+1'),
]);
更新某個(gè)字段的值:
Db::table('think_user')->where('id',1)->setField('name', 'thinkphp');
setField 方法返回影響數(shù)據(jù)的條數(shù),沒(méi)修改任何數(shù)據(jù)字段返回 0
自增或自減一個(gè)字段的值
setInc/setDec
如不加第二個(gè)參數(shù),默認(rèn)值為1
// score 字段加 1
Db::table('think_user')->where('id', 1)->setInc('score');
// score 字段加 5
Db::table('think_user')->where('id', 1)->setInc('score', 5);
// score 字段減 1
Db::table('think_user')->where('id', 1)->setDec('score');
// score 字段減 5
Db::table('think_user')->where('id', 1)->setDec('score', 5);
延遲更新
setInc/setDec
支持延時(shí)更新,如果需要延時(shí)更新則傳入第三個(gè)參數(shù)
下例中延時(shí)10秒,給score
字段增加1
Db::table('think_user')->where('id', 1)->setInc('score', 1, 10);
setInc/setDec 方法返回影響數(shù)據(jù)的條數(shù)
助手函數(shù)
// 更新數(shù)據(jù)表中的數(shù)據(jù)
db('user')->where('id',1)->update(['name' => 'thinkphp']);
// 更新某個(gè)字段的值
db('user')->where('id',1)->setField('name','thinkphp');
// 自增 score 字段
db('user')->where('id', 1)->setInc('score');
// 自減 score 字段
db('user')->where('id', 1)->setDec('score');
快捷更新(V5.0.5+
)
V5.0.5+
以上版本封裝的data
、inc
、dec
和exp
方法屬于鏈?zhǔn)讲僮鞣椒?,可以配?code style="box-sizing: inherit; -webkit-tap-highlight-color: transparent; text-size-adjust: none; -webkit-font-smoothing: antialiased; font-family: Consolas, "Liberation Mono", Menlo, Courier, monospace; font-size: 1em; display: inline-block; border-radius: 4px; padding: 2px 6px; background: rgb(249, 250, 250); word-break: break-all; white-space: pre; line-height: 1.3; border: 1px solid rgb(222, 217, 217); margin: 0px 5px;">update使用(官方推薦用法)。
下面舉個(gè)例子說(shuō)明用法:
Db::table('data')
->where('id',1)
->inc('read')
->dec('score',3)
->exp('name','UPPER(name)')
->update();