A-A+

PHP框架-laravel-数据库操作

2016年10月03日 Laravel, php 暂无评论 阅读 5,139 views 次

laravel数据库配置

只需要配置.env/config/database.php这2个文件。

laravel数据库操作——实现CURD

一、DB facade(结构型)

使用原始sql操作数据库

1、增加记录

$insert = DB::insert('insert into blog_student(name,age) values(?,?)',['imdupeng',20]);

2、修改更新记录

$update = DB::update('update blog_student set name=?,age=? where id=?',['imdupeng',19,1001]);

3、查询记录

$students = DB::select('select * from blog_student');

4、删除记录

$delete = DB::delete('delete from blog_student where id = ?',[1002]);

5、添加多条记录

$students = [['lala1',18],['nan1',19]];

foreach ($students as $student)

{

$insert = DB::insert('insert into blog_student(name,age) values(?,?)',[$student[0],$student[1]]);

echo 'add student:'.$student[0].' success
';

}

二、查询构造器

1、查询构造器介绍

laravel查询构造器(query builder)提供方便、流畅的接口,用来建立及执行数据库查找语法;

使用PDO参数绑定,保护应用程序免于SQL注入,传入的参数不需要额外转义特殊字符;

基本可以满足所有的数据库操作,且在所有支持的数据库系统上都可以执行。

2、新增数据

增加1条数据:(返回布尔值)
$add = DB::table('student')->insert(['name'=>'imdupeng','age'=>18]);

//使用查询构造器对批量添加更方便 (返回布尔值)

$add2 = DB::table('student')->insert([

['name'=>'imdupeng2','age'=>18],

['name'=>'imdupeng3','age'=>19]

]);

//返回新增加的id

$id = DB::table('student')-><span style="color: #ff0000;">insertGetid</span>(['name'=>'tianyi','age'=>29]);

3、更新修改数据

$update = DB::table('student')->where('id',1010)->update(['name'=>'dp','age'=>22]);
$update = DB::table('student')->where(['id'=>1010])->update(['name'=>'dupeng','age'=>29]);
//自增
$update = DB::table('student')->where('id',1010)->increment('age');
$update = DB::table('student')->where('id',1010)->increment('age',3);
//自减
$update = DB::table('student')->where('id',1010)->decrement('age');

4、删除数据

$del = DB::table('student')
	->where('id',1015)
	->delete();

//清空表中所有数据,使用truncate
$delall = DB::table('student')->truncate();

5、查询数据,查询构造器返回的是对象
laravel使用查询构造器查询数据,有以下几个方法:get()、first()、where()、pluck()、lists()、select()、chunk()

//get(),返回所有数据,以对象的形式返回
$students = DB::table('student')->get();
//只返回第一条数据,对象
$firststudent = DB::table('student')->first();
//获取id倒序排序后的第一条数据
$firstorderstudent = DB::table('student')->orderBy('id','desc')->first();
//使用where()条件获取数据
$wherestudent = DB::table('student')->where('id','>=',1012)->get();
//使用where()条件获取第一条数据
$wherestudent = DB::table('student')->where('id','>=',1012)->first();
//使用whereRaw()多个条件,查询数据
$data = DB::table('student')->whereRaw('id >= ? and age >= ?',[1012,20])->get();
//使用pluck,返回结果集中指定的1个字段
$names = DB::table('student')->whereRaw('id >= ? and age >= ?',[1012,20])->pluck('name');
//使用pluck,返回结果集中指定的1个字段,并由id作为键名
$id_names = DB::table('student')->whereRaw('id >= ? and age >= ?',[1012,20])->pluck('name','id');
$id_names = DB::table('student')->whereRaw('id >= ? and age >= ?',[1012,20])->lists('name','id');
//使用lists()与pluck类似,我这里使用lists报错undefined。
$names = DB::table('student')->lists('name');    //知道原因的请告知一下
//查询的时候指定部分字段
$students = DB::table('student')->select('id','name','age')->get();
/* 分段获取-每次查2条 */
DB::table('student')->chunk(2,function($students){
	dd($students);
});

6、查询构造器中的聚合函数,如:count()、max()、min()、avg()、sum()等。演示如下:

/* 查询构造器中的聚合函数 */
$count = DB::table('student')->count();
//注意,以下需要添加处理的字段名
$max = DB::table('student')->max('age');
$min = DB::table('student')->min('age');
$avg = DB::table('student')->avg('age');
$sum = DB::table('student')->sum('age');

三、Eloquent ORM (对象关系映射:Object Relation Mapping)

ORM是laravel操作数据库最常见、最方便的方式!

1、ORM简介

laravel自带的ORM是一个优美、简洁的ActiveRecord实现,用来实现数据库操作
每个数据表都有一个与之对应的模型(model),用于和数据表交互。

2、模型的建立

使用ORM处理的数据表,都要创建一个与之对应的模型文件。
例如:操作student表,就在App目录下创建一个student.php的模型文件,内容如下:

<!--?php <br ?-->namespace App;
use Illuminate\Database\Eloquent\Model;
class Student extends Model {
	protected $table = 'student';	//指定表名
	protected $primaryKey = 'id';	//指定主键,如果主键是‘id’就不需要这一句。
}

建立好student表的对象后,就可以在controller中直接使用该对象。当然要先use一下。

3、查询数据

$students = Student::all();    //查询所有满足条件的。
$student = Student::find(1001);   //查询一条数据,‘1001’这是主键id。
$student = Student::findOrFail(1001);   //查询一条数据,查询不到就报错。

4、查询构造器在ORM中的使用

查询构造器同样可以在ORM中使用,而且非常重要。

Student::get();    //查询所有满足条件的。
Student::first();    //查询第一条数据
Student::where('id','>=','1001')->orderBy('age','desc')->get();    //带条件的查询
Student::chunk(2,function($students){
	dd($students);
});
//聚合函数,如下
$max = Student::max('age');
$min = Student::min('age');
$avg = Student::avg('age');
$sum = Student::sum('age');
//带条件的聚合函数
$max = Student::where('id','>=','1010')->max('age');

5、新增数据、自定义时间戳、批量赋值

方法一:通过模型新增数据(涉及自定义时间戳)

$student = new Student();
		$student->name = 'dp3';
		$student->age = 19;
		$bool = $student->save();

会自动完成created_at和updated_at字段。
要关闭自动填充时间字段,在student的model文件设置如下:

//关闭更新自动时间
public $timestamps = false;

但是默认的时间存储格式是“2016-10-03 14:16:16”,如下方法可以改为时间戳:

public $timestamps = true;
protected function getDateFormat()
{
	return time();
}

但是输出出来的时间,系统会自动转为格式化好的格式,我们需要时间戳,怎么办?

echo Student::find(1019)->created_at;    //可以看到默认输出的是2016-10-03 14:25:37格式

那么我们可以继续修改model文件,

public $timestamps = true;
	protected function getDateFormat()
	{
		return time();
	}
	protected function asDateTime($returntime)
	{
		return $returntime;
	}

方法二:使用模型的create方法新增数据(涉及批量赋值)

$student = Student::create(
			['name'=>'tianshi','age'=>29]		
		);

默认此方法会报错“MassAssignmentException”!是因为批量赋值默认不被允许,需要在model里设置允许的批量赋值字段,方法如下:

protected $fillable = ['name','age'];    //允许的批量赋值字段

当然也可以设置不允许的批量赋值字段,如下:

protected $guarded = ['email','passwd'];  //不允许的批量赋值字段

还有2个特别的方法:

//firstOrCreate(),查找,如果不存在则创建并保存
$student = Student::firstOrCreate(
	['name'=>'jack','age'=>18]
);
		
//firstOrNew(),查找,如果不存在则创建(并不会保存)。
$student = Student::firstOrNew(
	['name'=>'jack','age'=>18]
);
$bool = $student->save();  //save()之后才会保存

5、修改数据

方法一:通过模型更新

$student = Student::find(1019);
$student->name = 'kitty';
$bool = $student->save();

方法二:结合查询语句批量更新

$num = Student::where('id','>=',1017)->update(
	['age'=>50]
);

6、删除数据

方法一:通过模型删除

$student = Student::find(1020);
$bool = $student->delete();

方法二:通过主键删除

//以下三种方式都可以
$num = Student::destroy(1021);
$num = Student::destroy(1021,1018);
$num = Student::destroy([1021,1018]);

方法三:通过指定条件删除

$num = Student::where('id','>=',1017)->delete();

好了Laravel的所有操作数据库方式到此结束。

标签:

给我留言