zoukankan      html  css  js  c++  java
  • tp5数据库——更新数据

    更新数据

    更新数据表中的数据

    Db::table('think_user')->where('id', 1)->update(['name' => 'thinkphp']);

    如果数据中包含主键,可以直接使用:

    Db::table('think_user')->update(['name' => 'thinkphp','id'=>1]);

    update 方法返回影响数据的条数,没修改任何数据返回 0

    如果要更新的数据需要使用SQL函数或者其它字段,可以使用下面的方式:

    Db::table('think_user')
        ->where('id', 1)
        ->update([
            'login_time'  => ['exp','now()'],
            'login_times' => ['exp','login_times+1'],
        ]);

    V5.0.18+版本开始是数组中使用exp查询和更新的话,必须改成下面的方式:

    Db::table('think_user')
        ->where('id', 1)
        ->update([
            'login_time'  => Db::raw('now()'),
            'login_times' => Db::raw('login_times+1'),
        ]);

    更新某个字段的值

    Db::table('think_user')->where('id',1)->setField('name', 'thinkphp');

    setField 方法返回影响数据的条数,没修改任何数据字段返回 0

    自增或自减一个字段的值

    setInc/setDec 如不加第二个参数,默认值为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支持延时更新,如果需要延时更新则传入第三个参数
    下例中延时10秒,给score字段增加1

    Db::table('think_user')->where('id', 1)->setInc('score', 1, 10);

    setInc/setDec 方法返回影响数据的条数

    助手函数

    // 更新数据表中的数据
    db('user')->where('id',1)->update(['name' => 'thinkphp']);
    // 更新某个字段的值
    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+以上版本封装的dataincdecexp方法属于链式操作方法,可以配合update使用(官方推荐用法)。

    下面举个例子说明用法:

    Db::table('data')
        ->where('id',1)
        ->inc('read')
        ->dec('score',3)
        ->exp('name','UPPER(name)')
        ->update();
  • 相关阅读:
    Python 虚拟环境 virtualenv
    Python
    开发语言之---Java
    LINUX系统
    关系型数据库之MySQL
    开发语言之---Python
    框架之---Django
    递归/面向过程编程
    迭代器/生成器函数及协程函数的编写和使用
    装饰器的编写及使用
  • 原文地址:https://www.cnblogs.com/fei-H/p/11763581.html
Copyright © 2011-2022 走看看