Laravel中对数据库进行增删改查操作

本文详细介绍了如何在Laravel框架中进行数据库的增删改查操作,包括插入数据并获取自增ID,查询全部和特定条件的数据,更新记录如加一和减一操作,以及不同方式的删除数据,包括重置自增ID。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

插入数据
  1. 插入一条数据
 DB::table('users')->insert([
    'name' => str_random(10),
    'email' => str_random(8) . '@163.com',
    'password' => bcrypt('secret')
]);
  1. 返回自增ID
$userId = DB::table('users')->insertGetId([
    'name' => str_random(10),
    'email' => str_random(8) . '@qq.com',
    'password' => bcrypt('secret')
]);
查询数据
  1. 查询所有数据
DB::table('users')->get();
  1. 查询数据的第一条
$user = DB::table('users')->where('name', $name)->first();
  1. 查询多个字段
$user = DB::table('users')->select('id', 'name', 'email')->where('name', $name)->first();
  1. 条件查询
$user = DB::table('users')->where('name', $name)->get();
更新数据
  1. 更新数据
DB::table('users')->where('id', '>', $id)->update(['name' => str_random(8)]);
  1. 加一操作
DB::table('posts')->where('id', 100)->increment('views');
  1. 减一操作
DB::table('posts')->where('id', 100)->decrement('votes');  
删除数据
  1. 删除一条数据
DB::table('users')->where('id', '>=', $id)->delete();
  1. 删除所有
 DB::table('users')->delete();
  1. 删除所有数据并重置自增id
DB::table('users')->truncate();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值