16.构造器的增删改

学习要点:
1.增删改操作
本节课我们来开始学习数据库的构造器查询中增删改操作。
一.增删改操作
1. 使用 insert()方法可以新增一条或多条记录;
//新增一条记录
DB::table('users')->insert([
'username' => '李白',
'password' => '123456',
'email' => 'libai@163.com',
'details' => '123'
]);
//新增多条记录
DB::table('users')->insert([
[...],
[...]
]);
2. 使用 insertOrIgnore()方法,可以忽略重复插入数据的错误;
//忽略重复新增数据的错误
DB::table('users')->insertOrIgnore([
'id' => 304,
'username' => '李白',
'password' => '123456',
'email' => 'libai@163.com',
'details' => '123'
]);
3. 使用 insertGetId()方法,获取新增后的自增 ID;
//获取新增后返回的 ID
$id = DB::table('users')->insertGetId([
'username' => '李白',
'password' => '123456',
'email' => 'libai@163.com',
'details' => '123'
]);
return $id;
4. 使用 update()方法,可以通过条件更新一条数据内容;
//更新修改一条数据
DB::table('users')->where('id', 304)
->update([
'username' => '李红',
'email' => 'lihong@163.com'
]);
5. 使用 updateOrInsert()方法,可以先进行查找修改,如不存在,则新增;
//参数 1:修改的条件
//参数 2:修改的内容(新增的内容)
DB::table('users')->updateOrInsert(
['id'=>307],
['username'=>'李黑', 'password'=>'654321', 'details'=>'123']
);
6. 对于 json 数据,新增和修改的方法和正常数据类似;
//新增时,转换为 json 数据
'list' => json_encode(['id'=>19])
//修改时,使用 list->id 指定
DB::table('users')->where('id', 306)
->update([
'list->id' => 20
]);
7. 更新数据时,可以使用自增 increment()和自减 decrement()方法;
//默认自增/自减为 1,可设置
DB::table('users')->where('id', 306)->increment('price');
DB::table('users')->where('id', 306)->increment('price', 2);
8. 使用 delete()删除数据,一般来说要加上 where 条件,否则清空;
//删除一条数据
DB::table('users')->delete(307);
DB::table('users')->where('id', 307)->delete();
//清空
DB::table('users')->delete();
DB::table('users')->truncate();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值