首页 Order Laravel 正文

Laravel 构造器的增删改

金鹏头像 金鹏 Laravel 2022-04-01 11:04:01 0 292
导读:一.增删改操作1.使用insert()方法可以新增一条或多条记录;//新增一条记录DB::table('users ')->insert([&...
.增删改操作

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();


本文地址:https://www.jinpeng.work/?id=161
若非特殊说明,文章均属本站原创,转载请注明原链接。
广告3

欢迎 发表评论:

  • 请填写验证码

日历

«    2025年4月    »
123456
78910111213
14151617181920
21222324252627
282930

控制面板

您好,欢迎到访网站!
  查看权限
广告2

退出请按Esc键