摘要:一.新增操作public function insert() { $res = DB::table('goods')->insert([ 'name'=>'华为
一.新增操作
public function insert()
{
$res = DB::table('goods')->insert([
'name'=>'华为',
'price'=>'6999',
'desc'=>'国产荣耀!!!凑字数凑字数凑字数凑字数凑字数凑字数凑字数凑字数',
'create_time'=>time()
]);
var_dump($res);
}

insert(['字段名1'=>'值1','字段名2'=>'值2'....]) 返回受影响记录数
insertGetId()返回新增的主键
--------------------------------------------------------------------------------
二.更新操作
public function update(Request $request)
{
//获取路由参数
$id = $request->route('id');
//执行更新,条件为id=路由参数
$res = DB::table('goods')->where('id',$id)->update([
'price'=>6988
]);
dump($res);
}
update(['更新字段1'=>'新值1','更新字段2'=>'新值2'....])返回受影响条数
自增increment('字段',自增值) 自减decrement('字段',自增值)
-------------------------------------------------------------------------------
三.删除操作
public function delete(Request $request)
{
//获取路由参数
$id = $request->route('id');
//删除id大于路由参数的数据
$res = DB::table('goods')->where('id','>',$id)->delete();
dump($res);
}
四.查询操作
1.全部查询 get()
$res = DB::table('goods')->get();
2.单条查询 first()第一条 find(主键)
$res = DB::table('goods')->find(12); //id=12$res = DB::table('goods')->first(); //第一条 3.查询一个指定字段的值 value('字段')
$res = DB::table('goods')->where('id',22)->value('name'); //id=22的name的值
4.查询一列的数据 pluck('值','字段的值')
$res = DB::table('goods')->where('id','>',20)->pluck('price','name'); //查询id>20的产品名=>价格
5.分组查询 chunk('分组数',闭包) 不过每太明白 这个有什么用 分组数起到了什么作用呢?
$list = [];
$res = DB::table('goods')->orderByDesc('price')->chunk(2,function ($products) use(&$list){
foreach ($products as $pro){
if($pro->id>20){
$list[] = ['id'=>$pro->id,'name'=>$pro->name]; //id>20 将id的值 和名字的值 放入存储数组
}
}
});
dump($list);
6.跳过某些字段查询 skip(跳过数)->take(取出几个)->get() offset('偏移量')->limit()->get()
$res = DB::table('stu')->offset(2)->limit(3)->get();
$res = DB::table('stu')->skip(2)->take(2)->get();
7.and or where([['字段1','条件','值1'],['字段1','条件','值1']....]) orWhere(['字段1','条件','值1'],['字段1','条件','值1']....])
$res = DB::table('goods')->orWhere([['id','>',20],['price','>',7000]])->get(); //id>20或者price>7000
8.原生写法查询 whereRaw('原生条件')
$res = DB::table('goods')->whereRaw('id>3')->limit(5)->get();
9.集合 区间查询 whereBetween('字段',['起始',结束'']) whereIn('字段',[值1,值2,值3...])匹配这些值
$res = DB::table('goods')->whereBetween('price',[7000,8000])->get(); //价格在7000-8000之间
$res = DB::table('goods')->whereIn('id',[22,23,24])->get(); //id等于22 23 24的
10.随机查询 inRandomOrder() 每次刷新随机获取
$res = DB::table('goods')->inRandomOrder()->first(); //随机获取一个 11.设置要查查询的字段 select(字段1,字段2..) addSelect(字段)添加限制字段
$res = DB::table('goods')->select('name','price','create_time')->addSelect('id')->limit(4)->get(); //获取4条数据 仅获取name等三个字段 并追加查询一个id字段
12.原生写法限制字段 selectRaw('字段1,字段2,字段3')
$res = DB::table('goods')->selectRaw('name,price,create_time')->addSelect('id')->limit(4)->get();
批改老师:查无此人批改时间:2019-01-22 16:39:20
老师总结:作业完成的不错,代码整洁,注释也不错,继续加油。