生活随笔
收集整理的這篇文章主要介紹了
十六、PHP框架Laravel学习笔记——构造器的增删改
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一.增刪改操作
使用 insert()方法可以新增一條或多條記錄;
DB::table('users')->insert([ 'username' => '李白', 'password' => '123456', 'email' => 'libai@163.com', 'details' => '123' ]);
DB::table('users')->insert([ [...], [...] ]);
使用 insertOrIgnore()方法,可以忽略重復插入數據的錯誤;
DB::table('users')->insertOrIgnore([ 'id' => 304, 'username' => '李白', 'password' => '123456', 'email' => 'libai@163.com', 'details' => '123' ]);
使用 insertGetId()方法,獲取新增后的自增 ID;
$id = DB::table('users')->insertGetId([ 'username' => '李白', 'password' => '123456', 'email' => 'libai@163.com', 'details' => '123' ]);
return $id;
使用 update()方法,可以通過條件更新一條數據內容;
DB::table('users')->where('id', 304) ->update([ 'username' => '李紅', 'email' => 'lihong@163.com' ]);
使用 updateOrInsert()方法,可以先進行查找修改,如不存在,則新增;
DB::table('users')->updateOrInsert( ['id'=>307], ['username'=>'李黑', 'password'=>'654321', 'details'=>'123'] );
對于 json 數據,新增和修改的方法和正常數據類似;
'list' => json_encode(['id'=>19])
DB::table('users')->where('id', 306) ->update([ 'list->id' => 20 ]);
更新數據時,可以使用自增 increment()和自減 decrement()方法;
DB::table('users')->where('id', 306)->increment('price');
DB::table('users')->where('id', 306)->increment('price', 2);
使用 delete()刪除數據,一般來說要加上 where 條件,否則清空;
DB::table('users')->delete(307);
DB::table('users')->where('id', 307)->delete();
DB::table('users')->delete();
DB::table('users')->truncate();
總結
以上是生活随笔為你收集整理的十六、PHP框架Laravel学习笔记——构造器的增删改的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。