laravel框架数据库操作、查询构建器、Eloquent ORM操作实例分析

吾爱主题 阅读:119 2021-09-24 14:18:00 评论:0

本文实例讲述了laravel框架数据库操作、查询构建器、Eloquent ORM操作。分享给大家供大家参考,具体如下:

1、连接数据库

laravel连接数据库的配置文件位于config/database.php中,在其中connection字段中包含laravel所支持的数据库的配置信息,可以看到其中有主机、端口、数据库、用户名、密码等信息:

?
1 2 3 4 5 6 7 8 9 10 11 12 13 'mysql' => [    'driver' => 'mysql' ,    'host' => env( 'DB_HOST' , 'localhost' ),    'port' => env( 'DB_PORT' , '3306' ),    'database' => env( 'DB_DATABASE' , 'forge' ),    'username' => env( 'DB_USERNAME' , 'forge' ),    'password' => env( 'DB_PASSWORD' , '' ),    'charset' => 'utf8' ,    'collation' => 'utf8_unicode_ci' ,    'prefix' => '' ,    'strict' => false,    'engine' => null, ],

其中都是引入env文件中的默认值,laravel目录最外层有.env文件,在其中配置对应的默认值

DB_HOST=数据库服务器地址
DB_PORT=数据库端口
DB_DATABASE=数据库名
DB_USERNAME=用户名
DB_PASSWORD=密码

2、原生SQL操作数据库

在controller中对数据库进行增删改查的操作

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 public static function testDB(){    //增加一条数据    DB::insert( "insert into student(name,age) values(?,?)" ,[ 'sandy' ,19]);    //删除一条数据    DB:: delete ( 'delete from student where name=?' ,[ 'sandy' ]);    //修改一条数据    DB::update( 'update student set sex=? where name=?' ,[ '男' , 'tory' ]);    //查询数据    $res =DB::select( 'select * from student' );    //进行数据库通用操作    DB::statement( 'drop table users' );    //打印结果    dd( $res ); }

其中通过?占位符的方式进行了参数绑定,以此来防止数据库注入攻击,也可以通过命名绑定的方式:   

?
1 $res = DB::select( 'select * from users where id = :id' , [ 'id' => 1]);

3、通过查询构建器操作数据库

Laravel将常用的数据库操作封装为接口函数提供给用户调用,从而使数据库操作更为便捷,这些接口就是查询构建器(query builder)。而且通过PDO绑定的方式避免SQL注入攻击,在使用查询构建器时不必考虑过滤用户输入。

3.1、得到结果集

lavarel查询的返回结果集合是StdClass,可以通过$res->name类似访问对象属性的方式访问返回值。如果要查询整个表使用get(),查询表中一条数据使用first(),查询一条数据的某个字段用value(),查询表中所有数据的某个字段用pluck()

?
1 2 3 4 5 6 7 8 //get()返回表中所有数据 $res =DB::table( 'student' )->get(); //first()返回结果集中的第一条数据 $res =DB::table( 'student' )->where( 'id' , '1001' )->first(); //value()返回一条数据中的指定字段 $res =DB::table( 'student' )->where( 'id' , '1003' )->value( 'name' ); //pluck()返回结果集中name字段的所有值 $res =DB::table( 'student' )->pluck( 'name' );

当结果集中的数据过多时,可以通过分块的方式返回结果集,chunk函数第一个参数为分块的大小(以每块2个数据的方式返回结果集),第二个参数为回调函数,当其返回false时就停止结果集的返回:

?
1 2 3 4 5 6 DB::table( 'student' )->chunk(2, function ( $res ){    foreach ( $res as $user ){      var_dump( $user );      if ( $user ->id >=1003) return false;    } });

3.2、增删改查

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 //增加一条数据 DB::table( 'student' )->insert([ 'name' => '李four' , 'sex' => '男' , 'age' =>22]); //增加多条数据 DB::table( 'student' )->insert([    [ 'name' => 'wang五' , 'sex' => '女' , 'age' =>21],    [ 'name' => 'zhao六' , 'sex' => '女' , 'age' =>20], ]); //删除数据 DB::table( 'student' )->where( 'id' , '>=' ,1006)-> delete (); //删除整个表 DB::table( 'student' )->truncate(); //修改数据 DB::table( 'student' )->where( 'id' ,1005)->update([ 'sex' => '女' , 'age' =>21]); //自增increment、自减decrement,默认增1 DB::table( 'student' )->where( 'id' ,1005)->increment( 'age' ,2); //自增同时可以进行修改 DB::table( 'student' )->where( 'id' ,1005)->increment( 'age' ,1,[ 'sex' => '女' ]); //查询指定字段 $res =DB::table( 'student' )->select( 'name' , 'age' )->get();

3.3、查询条件

通过查询构建器的where方法可以添加数据库查询条件,where()接收三个参数:字段名、操作符、值,操作符如果是'='可以省略,例如查询id>=1003的数据:

?
1 $res =DB::table( 'student' )->where( 'id' , '>=' ,1003)->get();

也可以通过条件数组传入多个限制条件,比如查询id>=1003并且id<1005:

?
1 2 3 4 $res =DB::table( 'student' )->where([    [ 'id' , '>=' ,1003],    [ 'id' , '<' ,1005] ])->get();

通过orwhere()来连接两个并列条件,例如查询id>=1003或者id<1002的数据:

?
1 $res =DB::table( 'student' )->where( 'id' , '>=' ,1003)->orwhere( 'id' , '<' ,1002)->get();

whereBetween()查询位于某个区间的数据:

?
1 $res =DB::table( 'student' )->whereBetween( 'id' ,[1003,1006])->get();

when()来判断某个查询是否执行,例如当$order为true时,才会执行排序:

?
1 2 3 4 $order =false; $res =DB::table( 'student' )->when( $order , function ( $query ){    return $query ->orderBy( 'age' , 'desc' );       //$order为true时才执行此语句 })->get();

3.4、排序、分组、限定

?
1 2 3 4 5 6 7 8 //orderBy对age字段升序 $res =DB::table( 'student' )->orderBy( 'age' , 'asc' )->get(); //按照create_at字段进行时间排序 $res =DB::table( 'student' )->latest( 'create_at' )->get(); //分组 $res =DB::table( 'student' )->groupBy( 'sex' )->get(); //跳过一条数据后返回2条数据 $res =DB::table( 'student' )->skip(1)->limit(2)->get();

3.5、聚合函数

laravel查询构建器还提供了聚合函数用于操作查询的结果集,包括count(计数)、sum(求和)、avg(平均值)、max(最大值)、min(最小值),例如求年龄平均值:

?
1 $res =DB::table( 'student' )->avg( 'age' );

4、Eloquent ORM

ORM是对象关系映射(Object Relational Mapping)的简称,是一种实现面向对象编程语言里不同类型系统的数据之间的转换的技术,即将数据库中的数据按照对象的形式进行组织,可以便于面向对象的程序进行数据库操作,之前在学习mongoDB时使用过mongoose ORM组织mongoDB ,当时还没有意识到这是orm。

Laravel内置的Eloquent ORM提供了一种便捷的方式帮助你组织数据库数据,每张数据表都对应一个与该表进行交互的模型(Model),通过Model类,你可以对数据表进行查询、插入、更新、删除等操作。Eloquent ORM本质上是查询构建器,因此上面查询构建器所使用的方法Eloquent都可以使用。

4.1、创建Model

在app文件夹下新建model文件,每个数据库都需要对应一个model,例如创建一个Student模板类:

?
1 2 3 4 5 6 7 8 9 10 11 12 13 namespace App; use Illuminate\Database\Eloquent\Model; class Student extends Model {    //指定对应的表    protected $table = 'student' ;    //指定主键    protected $primaryKey = 'id' ;    //允许批量赋值的字段    protected $fillable =[ 'name' , 'age' ];    //不允许批量赋值的字段    protected $guarded =[ 'created_at' ]; }

模板类会默认对应小写首字母末尾加s的数据库,例如Student模板会在当前数据库中查找students表。如果需要自定义表名,则需要重写$table变量来指定表名。

Eloquent默认的主键为'id',且该字段为自增int型,如果需要自定义主键,可以通过$primaryKey来指定。

Eloquent默认会管理数据表的创建时间、更新时间,对应数据表中的created_at、updated_at字段,你需要在创建表时包含这两个字段。如果不需要管理,可以令public $timestamps = false;。否则会报错

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'updated_at' in 'field list'

也可以自定义两个时间为你数据库中的字段:

?
1 2 const CREATED_AT = 'my_create' ; const UPDATED_AT = 'my_update' ;

4.2、Eloquent操作数据库

  • 新增数据有两种方法,一是通过新建ORM实例,而是通过create方法。在使用create批量添加时,需要在模板中通过$fillable指定可以赋值的字段,也可以$guard指定不允许赋值的字段。
?
1 2 3 4 5 6 //新建实例并赋值、保存 $stu = new Student(); $stu ->name= 'orm2' ; $stu ->save(); //create方法批量添加数据 Student::create([ 'name' => 'orm3' , 'age' =>13]);
  • 删除数据也有两种方法,一是通过find方法删除指定主键,二是通过查询构建器:
?
1 2 3 4 //destroy删除指定主键值 Student::destroy(1006,1007); //通过查询构建器删除 Student::where( 'id' ,1008)-> delete ();
  • 修改数据:①通过ORM实例来修改并保存②通过查询构建器
?
1 2 3 4 5 6 //通过返回Student对象进行修改 $stu =Student::find(1005); $stu ->age=21; $stu ->save(); //通过查询构建器修改 Student::where( 'id' ,1005)->update([ 'age' =>22]);
  • 查找数据:
?
1 2 3 4 5 //查询表中所有记录 $table =Student::all(); //根据id查询一条数据 $row =Student::find(1002); dd( $table );

当然也可以通过构建器的get()、first()来获取数据

通过上面的增删改查可以看出Eloquent可以使用查询构建器的所有方法,除了增删改查外,还有where、聚合函数等。

希望本文所述对大家基于Laravel框架的PHP程序设计有所帮助。

原文链接:https://blog.csdn.net/theVicTory/article/details/80230428

可以去百度分享获取分享代码输入这里。
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

【腾讯云】云服务器产品特惠热卖中
搜索
标签列表
    关注我们

    了解等多精彩内容