• laravel - 查询构建器2


    插入语句

    insert

    1. 接受一个列名和值的数组
    DB::table('users')->insert([
        'email' => 'kayla@example.com',
        'votes' => 0
    ]);
    
    • 1
    • 2
    • 3
    • 4
    1. 传递数组数组一次插入多条记录
    DB::table('users')->insert([
        ['email' => 'picard@example.com', 'votes' => 0],
        ['email' => 'janeway@example.com', 'votes' => 0],
    ]);
    
    • 1
    • 2
    • 3
    • 4

    insertOrIgnore

    1. 插入数据库时​​忽略错误
    DB::table('users')->insertOrIgnore([
        ['id' => 1, 'email' => 'sisko@example.com'],
        ['id' => 2, 'email' => 'archer@example.com'],
    ]);
    
    • 1
    • 2
    • 3
    • 4

    insertUsing

    1. 插入新记录,同时使用子查询来确定应该插入的数据
     DB::table('pruned_users')->insertUsing([
        'id', 'name', 'email', 'email_verified_at'
    ], DB::table('users')->select(
        'id', 'name', 'email', 'email_verified_at'
    )->where('updated_at', '<=', now()->subMonth()));
    
    • 1
    • 2
    • 3
    • 4
    • 5

    自增 IDs

    1. insertGetId
    $id = DB::table('users')->insertGetId(
        ['email' => 'john@example.com', 'votes' => 0]
    );
    
    • 1
    • 2
    • 3

    更新语句

    update

    $affected = DB::table('users')
                  ->where('id', 1)
                  ->update(['votes' => 1]);
    
    • 1
    • 2
    • 3

    updateOrInsert

    更新数据库中的现有记录,不存在则创建

    使用第一个参数的列和值对来定位匹配的数据库记录。 如果记录存在,它将使用第二个参数中的值进行更新。如果找不到记录,将插入一条新记录。

    DB::table('users')
        ->updateOrInsert(
            ['email' => 'john@example.com', 'name' => 'John'],
            ['votes' => '2']
        );
    
    • 1
    • 2
    • 3
    • 4
    • 5

    自增与自减

    1. increment
    DB::table('users')->increment('votes');
    
    DB::table('users')->increment('votes', 5);
    
    • 1
    • 2
    • 3
    1. decrement
    DB::table('users')->decrement('votes');
    
    DB::table('users')->decrement('votes', 5);
    
    • 1
    • 2
    • 3
    1. 在操作期间,指定要更新的其他列
    DB::table('users')->increment('votes', 1, ['name' => 'John']);
    
    • 1

    删除语句

    1. delete
      从表中删除记录。返回受影响的行数
    $deleted = DB::table('users')->delete();
    
    $deleted = DB::table('users')->where('votes', '>', 100)->delete();
    
    • 1
    • 2
    • 3
    1. truncate
      从表中删除所有记录并将自动递增 ID 重置为零
    DB::table('users')->truncate();
    
    • 1
  • 相关阅读:
    直播视频处理过程
    【11.17+11.22+11.23】Codeforces 刷题
    职场经验|项目管理发展方向有哪些?
    (Note)C++数值标识符
    Vue3_2024_1天【Vue3创建和响应式,对比Vue2】
    【mac】如何在Mac系统Dock栏中插入空格/半透明隐藏应用程序
    【分布式缓存】关于 Memcached 的几个常见问题
    Java Double compare()方法具有什么功能呢?
    推荐系统 推荐算法 (小红书为例) 笔记 2
    无涯教程-JavaScript - DELTA函数
  • 原文地址:https://blog.csdn.net/m0_37873390/article/details/126122182