laravel查询构造器实现增删改查和聚合函数的使用
1.查询构造器-新增数据
//添加单条数据 $result = DB::table('student')->insert([ 'name' => 'kevin', 'age' => '18', ]);
//添加单条数据并返回自增ID值 $result = DB::table('student')->insertGetId([ 'name' => 'luke', 'age' => '21', 'sex' => '1', ]);
//添加多条数据 $result = DB::table('student')->insert([ [ 'name' => 'mark', 'age' => '22', 'sex' => '1', ], [ 'name' => 'charles', 'age' => '23', 'sex' => '1', ], ]);
2.查询构造器-修改数据
//修改指定字段数据 $num = DB::table('student') ->where(['name'=>'小田']) ->update(['age'=>24]);
//increment:自增 $num = DB::table('student') ->increment('age',2);
//decrement:自减,并且修改其他字段 $num = DB::table('student') ->where(['id'=>9]) ->decrement('age',2, ['name'=>'mark']);
3.查询构造器-删除数据
$num = DB::table('student') ->where('id','>',7) ->delete();
4.查询构造器-查询数据
//get:查询多条数据 $result = DB::table('student') ->whereRaw('id > ? and age > ?', [1, 18]) ->get();
//first:查询单条数据 $result = DB::table('student') ->orderBy('id', 'desc') ->first();
//pluck:返回单个指定字段 $result = DB::table('student') ->whereRaw('id > ? and age > ?', [1, 18]) ->pluck('name');
//select:返回多个指定字段 $result = DB::table('student') ->whereRaw('id > ? and age > ?', [1, 18]) ->select('id','name') ->get();
//chunk:将集合分割成指定大小的集合
$result = DB::table('student') ->get() ->chunk(2);
5.查询构造器-聚合函数
//count:查询指定字总记录数 $result = DB::table('student')->count();
//max:查询指定字最大值 $result = DB::table('student')->max('age');
//min:查询指定字最小值 $result = DB::table('student')->min('age');
//avg:查询指定字平均值 $result = DB::table('student')->avg('age');
//sum:查询指定字总和 $result = DB::table('student')->sum('age');
更多请查看laravel手册:https://learnku.com/docs/laravel/8.x/queries/9401
【版权申明】未经博主同意,谢绝转载!(请尊重原创,博主保留追究权) https://www.cnblogs.com/facetwitter/p/15781254.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了