1.DB facade实现curd
$result = DB::select('select * from student');
$bool = DB::insert('insert into student(name, age) values(?, ?)', ['zhangsan', 18]);
$num = DB::update('update student set age = ? where id=?', [20, 1]);
$num = DB::delete('delete from student where id= ? ', [1]);
2.查询构造器
1)查询
$boole = DB::table('student')->insert(['name'=>'zhangsan', 'age'=>12]);
$insertId = DB::table('student')->insertGetId(['name'=>'zhangsan', 'age'=>12]);
$boole = DB::table('student')->insert([['name'=>'zhangsan', 'age'=>12],['name'=>'zhangsan', 'age'=>12],['name'=>'zhangsan', 'age'=>12]]);
2)更新
$num = DB::table('student')->where('id', 12)->update(['age'=>20]);
$num = DB::table('student')->where('id', 23)->increment('age', 2);
$num = DB::table('student')->where('id', 23)->decrement('age', 2);
$num = DB::table('student')->where('id', 23)->decrement('age', 2, ['name'=>23]); //自减时同时修改其他数据
2)删除
$num = DB::table('student')->where('id', 1)->delete();
$num = DB::table('student')->where('id', '>', 1)->delete();
DB::table('student')->truncate();
3)使用查询构造器查询数据
$resutl = DB::table('student')->get(); //获取所有的记录
$firstData = DB::table('student')->where('id', '>', 1)->orderBy('id', 'desc')->first(); //获取第一条记录
$result = DB::table('student')->whereRaw('id >? and age > ?', [1,2])->get(); //whereRaw()可以写多个条件
$result = DB::table('student')->whereRaw('id >? and age > ?', [1,2])->pluck('name'); //pluck返回一个字段
$result = DB::table('student')->whereRaw('id >? and age > ?', [1,2])->lists('name', 'id'); //lists返回一个字段,第二个参数是返回以某个字段为键
$result = DB::table('student')->select('id', 'name', 'age')->whereRaw('id >? and age > ?', [1,2])->get(); //select()指定字段
DB::table('student')->chunk(10, function($students) {
return false;//这个是查询一部分的时候直接跳出
}); //chunk()每次获取多少条
2.查询构造器中的聚合函数
$num = DB::table('student')->count(); //统计
$max = DB::table('student')->max('age'); //返回最大数
$max = DB::table('student')->sum('age'); //返回最大数
$max = DB::table('student')->min('age'); //返回最大数
3.数据库操作之-Eloquent ORM
$student = Student::all();
$student = Student::find(1); //根据主键进行查找
Student::findOrFail(100); //根据主键进行查找,如果没有查到进行报错
Student::get();
Student::first();
Student::chunk(100, function($students){});