本文实例讲述了laravel框架模型和数据库基础操作。,具体如下:
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方法
$id=DB::table("vipinfo")->insertGetId(['vip_ID'=>5,'vip_name'=>'wyp','vip_type'=>"出行",'vip_fenshu'=>800]);
echo $id;
//插入多条数据
$bool=DB::table("vipinfo")->insert([
['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")->where('vip_ID','>=',2)->get(); //一个条件
$student=DB::table("vipinfo")->whereRaw('vip_ID> ? and vip_fenshu >= ?',[2,300])->get(); //多个条件
dd($student);
//pluck()指定字段,后面不加get
$student=DB::table("vipinfo")->pluck('vip_name');
dd($student);
//lists()指定字段,可以指定某个字段作为下标
$student=DB::table("vipinfo")->lists('vip_name','vip_ID'); //指定vip_ID为下标
dd($student);
$student=DB::table("vipinfo")->lists('vip_name'); //不指定下标,默认下标从0开始
//select()指定某个字段
$student=DB::table("vipinfo")->select('vip_name','vip_ID')->get();
dd($student);
//chunk()每次查n条
$student=DB::table("vipinfo")->chunk(2,function($students){ //每次查2条
var_dump($students);
if(.......) return false; //在满足某个条件下使用return就不会再往下查了
});







