博客列表 >Laravel基础2(链式查询和CURD操作)

Laravel基础2(链式查询和CURD操作)

高杰
高杰原创
2020年06月19日 15:42:48822浏览

准备:创建数据库表Article,有id,cat_id,title,uid 4个字段,并填充数据;数据库表Users,有id,username,userpwd 3个字段。

1、链式查询

(1)查询单条数据需要用first();语句如下:

DB::table('article')->where('id',1)->first();  //查询ID为1的字段

(2)查询多条数据需要用get();语句如下:

DB::table('article')->get();    //查询出来的是个类,取出需要的数据,需要加上all()

DB::table('article')->get()->all();    //查询article表中的全部数据

DB::table('article')->select('cat_id as cid','title')->get()->all();    //只查询article表中的cat_id、title字段

DB::table('article')->where('id','>','3')->get()->all();     //只查询article表中ID大于3的数据

DB::table('article')->where('title,'like','%技术%')->get()->all();     //like查询,建议用 技术%,查询不出来采用 %技术%

DB::table('article')->where('title,'like','%技术%')->where('cat_id',5)->get()->all();     //多个where的and查询

DB::table('article')->where('cat_id,5)->orwhere('cat_id',8)->get()->all();     //多个whre可以or查询

DB::table('article')->where('cat_id,5)->orwhere('cat_id',8)->get()->all();     //多个whre可以or查询

DB::table('article')->where('cat_id,5)->orwhere('cat_id',8)->tosql();     //直接输出sql语句,输出的sql语句为参数化查询,进行了参数绑定

上边语句输出sql:select * from article where cat_id=? or cat_id=?;    第2步php传入参数 cat_id[0]=5,cat_id[1]=8

DB::table('article')->whereIn('cat_id,[1,4,5])->get()->all();    //whereIn查询,传入参数为数组,建议参数不要超过200个,不然效率会极速下降

DB::table('article')->join('users','users.id','=','article.uid')->seleclt('article.id','article.title','users.username')->get()->all();    //join查询

2、聚合函数

(1)计算平均值

DB::table('article')->avg('pv');    //计算平均值,默认是有小数的,如需去除小数,用int进行转换

(2)计算总数

DB::table('article')->count();    //计算总数,在innoDB中count(*)和count('id')相同,在MySIAM中count(*)更快

3、CURD操作

(1)插入一条数据

DB::table('article')->insert(array(6,1,'测试6',1));    

(2)插入多条数据

$item = array(6,1,'测试6',1);

$item2 = array(7,2,'测试7',2);

$data[] = $item;

$data[] = $item2;

DB::table('article')->insert($data);    

(3)插入一条数据并返回ID值

DB::table('article')->insertGetId(array(6,1,'测试6',1));    

(4)更新数据信息

DB::table('article')->where('id',6)->update(array('title'=>'测试666'));

DB::table('article')->whereIn('id',[6,7])->update(array('title'=>'测试666'));    //更新多条数据,用whereIn

(5)删除数据信息

DB::table('article')->where('id',6)->delete()

DB::table('article')->whereIn('id',[6,7])->delete();    //删除多条数据,用whereIn



声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议