laravel数据库操作有哪几种方式?怎样进行操作?
发布时间:2022-04-07 16:07:16 所属栏目:语言 来源:互联网
导读:这篇文章主要介绍的是laravel框架的数据库操作,包括DB facade[原始查找],查询构造器[Query Builder]和Eloquent ORM,小编觉得是比较实用的,有需要的朋友可以参考参考。 use IlluminateSupportFacadesDB; 1.DB facade[原始查找] $results = DB::select(
这篇文章主要介绍的是laravel框架的数据库操作,包括DB facade[原始查找],查询构造器[Query Builder]和Eloquent ORM,小编觉得是比较实用的,有需要的朋友可以参考参考。 use IlluminateSupportFacadesDB; 1.DB facade[原始查找] $results = DB::select('select * from users where id = :id', ['id' => 1]); DB::insert('insert into users (id, name) values (?, ?)', [1, 'Dayle']); 不返回值: DB::statement('drop table users'); 返回自增id: $id = DB::table('users')->insertGetId( ['email' => 'john@example.com', 'votes' => 0] ); $affected = DB::update('update users set votes = 100 where name = ?', ['John']); $num=DB::delete('delete from vipinfo where vip_ID= ?',[5]); 2.查询构造器[Query Builder] laravel查询构造器提供了方便流畅的接口,用来建立及执行数据库查找语法。使用了pdo参数绑定,使应用程序免于sql注入,因此传入的参数不需要额外转义特殊字符。基本上可以满足所有的数据库操作,而且在所有支持的数据库系统上都可以执行。 (1)新增 $bool=DB::table("vipinfo")->insert(['vip_ID'=>6,'vip_name'=>'zls','vip_type'=>"出行",'vip_fenshu'=>800]); echo $bool; //返回bool值 //如果想得到新增的id,则使用insertGetId方法 ['vip_ID'=>5,'vip_name'=>'wyp','vip_type'=>"出行",'vip_fenshu'=>800], ['vip_ID'=>6,'vip_name'=>'zls','vip_type'=>"出行",'vip_fenshu'=>800], ]); echo $bool; //返回bool值 (2)修改 $bool=DB::table("vipinfo")->where('vip_ID',6)->update(['vip_fenshu'=>500]); echo $bool; //自增 $bool=DB::table("vipinfo")->where('vip_ID',6)->increment("vip_fenshu");//自增1 $bool=DB::table("vipinfo")->where('vip_ID',6)->increment("vip_fenshu",3);//自增3 echo $bool; //自减 $bool=DB::table("vipinfo")->where('vip_ID',6)->decrement("vip_fenshu");//自1 $bool=DB::table("vipinfo")->where('vip_ID',6)->decrement("vip_fenshu",3);//自增3 echo $bool; //自增时再修改其他字段 $bool=DB::table("vipinfo")->where('vip_ID',6)->increment("vip_fenshu",3,['vip_name'=>'dbdibi']);//自增3 (3)删除 $num=DB::table("vipinfo")->where('vip_ID',6)->delete();//删除1条 $num=DB::table("vipinfo")->where('vip_ID','>',4)->delete();//删除多条 echo $num; //删除的行数 $num=DB::table("vipinfo")->truncate();//删除整表,不能恢复,谨慎使用 (4)查询 //get()返回多条数据 $student=DB::table("vipinfo")->get(); var_dump($student); //first()返回1条数据 $student=DB::table("vipinfo")->first(); //结果集第一条记录 $student=DB::table("vipinfo")->orderBy('vip_ID','desc')->first();//按vip_ID倒序排序 var_dump($student); //where()条件查询 $student=DB::table("vipinfo")->chunk(2,function($students){ //每次查2条 var_dump($students); if(.......) return false; //在满足某个条件下使用return就不会再往下查了 }); (编辑:常州站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |