学习要点:
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();
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交