DB facade实现CURD(操作数据库 手写原生SQL语句)
namespace AppHttpControllers; //控制器继承
use IlluminateSupportFacadesDB;
use AppStudent;
插入数据 (返回bool 插入是否成功) $result = DB::insert('insert into student(name,age) values(?,?)', [ 'abcd',23 ]);
$result = DB::table('student')->insert(['name' => 'Toky', 'age' => 19]); //插入多条数据参数改为二维数组即可
//更新数据(返回更新条数)
$num = DB::update('update student set age= ? where name=?)', [ 23,'abcd' ]);
$num = DB::table('student') ->where('id', 1023) ->update(['name'=>'query2','age'=>20]);
DB::table('as_admin')->where('id', 12)->increment('age', 3); //字段自增3写,默认为1 返回影响的行数
DB::table('as_admin')->where('id', 12)->decrement('age', 3); //字段自减3写,默认为1 返回影响的行数
DB::table('as_admin')->where('id', 12)->decrement('age', 3, array('name' => '张佳宁')); //自增或自减的同时更新name字段
//查询
DB::select('select * from student');
//get() 获取表中所有数据 $students = DB::table('student')->get()->toArray();;
//first() 获取第一条数据(随机),配合orderBy 一起使用
$students =DB::table('student')->orderBy('id','asc')->first()->toArray();;
//where 单条件查询
$students = DB::table('student')$students = DB::table('student') ->where('id', '>=', 20) ->get()->toArray();;
//where 多条件查询
$students = DB::table('student')$students = DB::table('student') ->whereRaw('id >= ? and age > ?',[18,20]) ->get()->toArray();;
//pluck 取结果集中一列特定列,返回字符串类型
$students = DB::table('student') ->pluck('id','name','age')->toArray();;
//lists 按照Key=>value 对 的方式返回数组;最多两个参数,第一个参数作为value,第二个做为key。一个参数时与pluck用法一样
$students = DB::table('student') ->whereRaw('id >= ? and age > ?',[18,20]) ->lists('id','name','age')->toArray();;
//select() 指定查询的字段
$students = DB::table('student') ->select('id','name','age') ->get()->toArray();;
//chunk() 方法 指定一次返回多少条,后跟闭包(匿名函数)
DB::table('student')->chunk(2,function($students){ var_dump($students->toArray();); }); //每次查两条然后输出到页面,不断查询、打印直至查询完所有数据,return false;则直接结束
//删除(返回删除条数)
$num = DB::delete('delete from')
DB::table('student')->where('id','>=',15)->delete();
DB::table('student')->truncate(); //删除表中所有数据,不建议使用
使用model(Eloquent ORM)进行curd
1、模型的声明
<?php namespace App; use IlluminateDatabaseEloquentModel; class Student extends Model{ protected $table = 'student'; //默认的表名是model名字的复数(加s) protected $primaryKey = 'id'; }
$student= new AppGoods();
$student= $student->all()->toArray();;
$student= $student->where('id', '1')->first()->toArray();
$student= $student->find([1,2,3,4])->toArray();//查找主键
$student= $student->save(['id'=>'10','age'=>20]);保存或更新