• 8.thinkphp框架数据库


    1.连接器和查询构造器

    image-20211109141106301

    同之前版本相比, ThinkPHP5的数据库操作对底层进行优化设计对各种操作进行高级封裝。既可以直接使用连接器进行高效的原生査询,也可以使用封装好的查询构造器进行直观便捷的查询,为模型操作打下基础。

    2.连接数据库

    image-20211109141519891

    2.1静态连接

    image-20211109141608182

    同样数据库配置文件 , 我们也可以在自定义配置文件下新建 , 返回的是一个数组

    database.php

    <?php
    return [
        // 数据库类型
        'type'            => 'mysql',
        // 服务器地址
        'hostname'        => '127.0.0.1',
        // 数据库名
        'database'        => 'tp5',
        // 用户名
        'username'        => 'root',
        // 密码
        'password'        => 'root',
        // 端口
        'hostport'        => '3306',
        // 连接dsn
        'dsn'             => '',
        // 数据库连接参数
        'params'          => [],
        // 数据库编码默认采用utf8
        'charset'         => 'utf8',
        // 数据库表前缀
        'prefix'          => '',
        // 数据库调试模式
        'debug'           => true,
        // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
        'deploy'          => 0,
        // 数据库读写是否分离 主从式有效
        'rw_separate'     => false,
        // 读写分离后 主服务器数量
        'master_num'      => 1,
        // 指定从服务器序号
        'slave_no'        => '',
        // 是否严格检查字段是否存在
        'fields_strict'   => true,
        // 数据集返回类型
        'resultset_type'  => 'array',
        // 自动写入时间戳字段
        'auto_timestamp'  => false,
        // 时间字段取出后的默认时间格式
        'datetime_format' => 'Y-m-d H:i:s',
        // 是否需要进行SQL性能分析
        'sql_explain'     => false,
        // Builder类
        'builder'         => '',
        // Query类
        'query'           => '\\think\\db\\Query',
    ];
    

    测试

    <?php
    namespace app\index\controller;
    use think\Db;
    use think\Request;
    
    class Index
    {
        protected $request;
        public function __construct(Request $request)
        {
            $this->request = Request::instance();
        }
    
        public function index()
        {
            return '欢迎来到php中文网学习';
        }
        public function demo()
        {
           // 1.获取数据库连接实例/对象 , think下的Db.php
            $link = Db::connect();
            // 2.用连接实例调用查询类的查询方法
            $res = $link->table('staff')->select();
            // 3.输出查询结果
            dump($res);
        }
    }
    

    image-20211109142731266

    2.2动态连接

    将database.php修改文件名 , 使其失校

    <?php
    namespace app\index\controller;
    use think\Db;
    
    class Index
    {
        public function index()
        {
            return '欢迎来到php中文网学习';
        }
        public function demo()
        {
            $config = [
                'type'=>'mysql',
                'hostname'=>'localhost',
                'username'=>'root',
                'password'=>'root',
                'database'=>'tp5',
            ];
           // 1.获取数据库连接实例/对象 , think下的Db.php
            $link = Db::connect($config);
            // 2.用连接实例调用查询类的查询方法
            $res = $link->table('staff')->select();
            // 3.输出查询结果
            dump($res);
        }
    }
    

    image-20211109143340248

    动态还可以通过字符串连接

    mysql://root:1234@localhost:3306/thinkphp#utf8
    数据库类型:/用户名:密码@数据库地址:数据库端口/数据库名#字符集
    

    示例

    <?php
    namespace app\index\controller;
    use think\Db;
    
    class Index
    {
    
        public function index()
        {
            return '欢迎来到php中文网学习';
        }
        public function demo()
        {
            $config1 = 'mysql://root:root@localhost:3306/tp5#utf8';
           // 1.获取数据库连接实例/对象 , think下的Db.php
            $link = Db::connect($config1);
            // 2.用连接实例调用查询类的查询方法
            $res = $link->table('staff')->select();
            // 3.输出查询结果
            dump($res);
        }
    }
    

    上面的操作一般工作不常用 , 都是使用配置文件 , 下面介绍工作常用的

    // 1.配置好数据库的配置文件 , 默认是会自动连接
    <?php
    namespace app\index\controller;
    use think\Db;
    
    class Index
    {
    
        public function index()
        {
            return '欢迎来到php中文网学习';
        }
        public function demo()
        {
            $res = Db::table('staff')->select();
            dump($res);
        }
    }
    

    image-20211109144309477

    操作数据库的第一步就是数据库的连接,TP5提供了强大灵活的连接方式,特别是惰性连接支持,极大提高了连接效率(db()助手函数不支持),使用户的关注重点放在业务逻辑上,不必担心连接问题啦

    3.原生查询

    可以通过Connection类实现

    image-20211109144437402

    文件在think下的db目录中 , 使用演示

    <?php
    namespace app\index\controller;
    use think\Db;
    
    class Index
    {
        public function index()
        {
            return '欢迎来到php中文网学习';
        }
        public function demo()
        {
            $sql = 'select * from staff where salary > 4500';
            $res = Db::query($sql);
            dump($res);
        }
    }
    

    占位符

    <?php
    namespace app\index\controller;
    use think\Db;
    
    class Index
    {
        public function index()
        {
            return '欢迎来到php中文网学习';
        }
        public function demo()
        {
            $sql = 'select * from staff where salary > ?';   // ?占位 , 不推荐, 推荐命名占位
            $res = Db::query($sql,[4000]);
            dump($res);
        }
          public function demo1()
        {
            $sql = 'select * from staff where salary > :salary';   // 推荐命名占位
            $res = Db::query($sql,['salary'=>4800]);
            dump($res);
        }
    }
    

    更新操作

    public function demo3()    {        $sql = 'update staff set salary = salary+1000 where id=:id';        $res = Db::execute($sql,['id'=>1001]);        $sql1 = 'select * from staff where id = :id';        $res1 = Db::query($sql1,['id'=>1001]);        dump($res1);    }
    

    插入操作

        public function demo4()    {        $sql = "insert into staff (salary) values (:salary)";        $res = Db::execute($sql,['salary'=>'8000']);        $sql1 = 'select * from staff';        $res1 = Db::query($sql1);        dump($res1);    }
    

    删除操作

        public function demo5()    {        $sql = 'delete from staff where id=:id ';        $res = Db::execute($sql,['id'=>1003]);        $sql1 = 'select * from staff';        $res1 = Db::query($sql1);        dump($res1);    }
    

    Connection类实例通过入口类Db静态自动调用,不用显示写出

    因为数据库只能认别并运行原生SQL语句,所以对于数据库的一切查询操作,最终都要归结到原生查询。包括
    后面要学到的,利用查询构造器来进行增删改查操作,最终仍是调用连接类 Connection对应方法完成。

    4.查询构造器

    基本上框架的sql语句执行都是高度封装的 , 很少用原生sql语句查询 , 但是再封装最后还是要转成原生sql语句执行

    4.1工作原理

    image-20211109151840565

    对于用户来说 , 只需要掌握查询类的使用方法 , 然后调用生成类生成查询语句 , 然后连接类拿到语句去执行

    类库文件

    image-20211109152222614

    生成类是一个抽象类 , 不能够被实例化 , 连接器类Connect , 所有的sql语句最终都是交给他去执行完成的

    4.2链式操作

    链式操作的功能 : 快速生成查询条件

    链式操作所有的方法来自Query类

    链式操作的返回值就是当前的查询对象

    image-20211110142221124

    示例

    <?phpnamespace app\index\controller;use think\Db;class Index{    public function demo()    {        dump(            Db::table('staff')                ->field(['name','salary'])                ->where('id',1001)   // table和field ,where都是链式操作返回一个查询对象                ->find()  // 最终方法,返回一个数组        );    }}
    

    4.3查询条件的生成

    image-20211110142923874

    查询构造器如何生成查询条件 , 第三种闭包查询是常用的

    第一种

        public function demo()    {        dump(            Db::table('staff')                ->field(['name','salary'])                ->where('id',1001)   // table和field ,where都是返回一个查询对象 , 中间的表达式=可以省略                ->find()        );    }
    

    第二种 数组 适合多个条件

     public function demo()    {        dump(            Db::table('staff')                ->field(['name','salary'])                ->where([                    'id'=>['>',1000],                    'salary'=>['>',1000]                    ]                )   // table和field ,where都是返回一个查询对象                ->select() // 或者select()        );    }
    

    第三种 闭包函数

     public function demo()    {        dump(            Db::table('staff')                ->field(['name','salary'])                ->where(function ($query){                    $query->where('id','>',1000)                        ->where('salary','>',2000);                })                ->select() // 或者select()        );    }
    
    public function demo()    {        $salary = 2000;        dump(            Db::table('staff')                ->field(['name','salary'])                ->where(function ($query) use ($salary){                    $query->where('id','>',1000)                        ->where('salary','>',$salary);                })                ->select() // 或者select()        );    }
    

    image-20211110152929040

    4.4查询构造器实现CURD

    这些curd方法都是终极方法 , 能够直接对数据表完成读写操作

    image-20211110153154460

    增加一条记录

    image-20211110153242423

    增加多条记录

    image-20211110153325405

    更新数据

    image-20211110153359438

    自增操作

    image-20211110153455207

    输出一列数据

    image-20211110153628477

    删除一条记录

    image-20211110153726930

    删除多条记录用数组 , delete([1001,1103]) , 清空表 delete(true)

    查询条件的调用次序就是生成SQL条件的次序,推荐使用闭包,来生成查询条件,不仅功能强大,而且便于扩展。下节课开始学习模型操作,因为我们在开发过程,并不直接操作数据库,而是通过模型与数据库打交道。

  • 相关阅读:
    merge sorted array
    Remove Duplicates from Sorted List
    climbing stairs(爬楼梯)(动态规划)
    点击事件加不上,换个位置调用
    The file couldn’t be opened because you don’t have permission to view it
    网络——性能调优
    SDWebImage缓存图片的机制(转)
    本地推送 简单代码演示
    UILable点击事件
    点击背景键盘退下
  • 原文地址:https://www.cnblogs.com/xcymn/p/15712388.html
Copyright © 2020-2023  润新知