zoukankan      html  css  js  c++  java
  • 全栈微信小程序商城 学习笔记之七 数据库访问

    原生方法

    新建路由
    application oute.php

    Route::get('api/v1/banner/:id', 'api/v1.Banner/getBanner');
    

    新建模型类
    applicationapimodelBanner.php

    class Banner
    {
        public static function getBannerByID($id)
        {
          //
        }
    }
    

    配置连接数据库
    applicationdatabase.php

    return [
      'type' => 'mysql',
      'database' => 'zerg',
      'username' => 'root',
      'password' => '123456',
      'hostport' => '3306'
    ];
    

    tp5提供了db类来进行数据库的操作
    使用
    applicationapimodelBanner.php

    use thinkDb;
    
    class Banner
    {
        public static function getBannerByID($id)
        {
            $result = Db::query('select * from banner_item where banner_id=?', [$id]);
            return $result;
        }
    }
    

    调用
    applicationapicontrollerv1Banner.php

    class Banner
    {
        public function getBanner($id)
        {
            (new IDMustBePositiveInt())->goCheck();
            $banner = BannerModel::getBannerById($id);
            if (!$banner) {
                 throw new BannerMissException();
            }
            return json($banner);
        }
    }
    

    查看返回结果

    查询构造器

    tp5提供了query查询器,对原生的sql做了封装,通过builder编译生成原生sql,使用上更便利

    不需要关心具体的实现,可对多种不同的数据库统一操作,只需要在配置文件中配置

    applicationapimodelBanner.php

    class Banner
    {
        public static function getBannerByID($id)
        {
          // where的使用
          // where('字段名','表达式', '查询条件')
          // $result = Db::table('banner_item')->where('banner_id', '=', $id)->find();//返回一条结果
          $result = Db::table('banner_item')->where('banner_id', '=', $id)->select();//返回多条结果
          return $result;
        }
    }
    

    使用闭包法

    class Banner
    {
        public static function getBannerByID($id)
        {
          $result = Db::table('banner_item')
          ->where(function ($query) use ($id) {
            $query->where('banner_id', '=', $id);
          })
          ->select();
          return $result;
        }
    }
    
    

    开启sql日志记录

    class Banner
    {
        public static function getBannerByID($id)
        {
          $result = Db::table('banner_item')
          //加了fetchSql() 不会真实执行,只会返回一个最终生成sql代码,但不够详细(没有调用时间等)
          ->fetchSql()
          ->where(function ($query) use ($id) {
            $query->where('banner_id', '=', $id);
          })
          ->select();
          return $result;
        }
    }
    

    查看返回结果

    因为前面关闭了默认记录日志,只能手动记录
    publicindex.php

    require __DIR__ . '/../thinkphp/start.php';
    // 放置在加载框架引导文件之后
    	hinkLog::init([
        'type'  =>  'File',
        'path'  =>  LOG_PATH,
        'level' => ['sql']
    ]);
    

    测试:每次sql查询成功后将会保存日志

    ORM与模型

    Object Relation Mapping 对象关系映射
    以操作一个对象的方式来获取数据
    模型是根据功能划分的,不单单是一个对象一个表,也可以是多个对象组成,对应多个表。

    初识模型

    applicationapimodelBanner.php

    class Banner extends Model 
    {
      //...
    }
    

    使用
    applicationapicontrollerv1Banner.php

    class Banner
    {
        public function getBanner($id)
        {
            (new IDMustBePositiveInt())->goCheck();
            $banner = BannerModel::get($id);
            if (!$banner) {
                 throw new BannerMissException();
            }
            // 观察继承了Model的返回结果,返回了个模型对象,而不是像Db一样的数组
            // 可直接返回不再序列化处理,tp5会自动将模型对象序列化
            return $banner;
        }
    }
    

    再在config.php配置中更改默认输出类型可返回正常结果
    applicationconfig.php

    return [
      //...
      'default_return_type' => 'json',
      //...
    ]
    

    查看结果

    模型定义总结

    tp5默认表名和类名一致,如不是需要额外处理,例如下面的Banner模型关联的表就是cateory表

    class Banner extends Model 
    {
      protected $table = 'cateory'
      //...
    }
    

    用命令生成Model(在根目录执行)

    php think make:model api/BannerItem
    

    查看
    applicationapimodelBannerItem.php

    <?php
    namespace appapimodel;
    
    use thinkModel;
    
    class BannerItem extends Model
    {
        //
    }
    
  • 相关阅读:
    MySQL数据库高可用集群搭建-PXC集群部署
    高性能高并发网站架构,教你搭建Redis5缓存集群
    redis连接错误3种解决方案System Error MISCONF Redis is configured to save RDB snapshots
    进程异常行为-反弹Shell攻击,KILL多个进程
    Laravel中我们登录服务器通过 Tinker 手动创建后台管理用户
    Laravel5.x的php artisan migrate数据库迁移创建操作报错SQLSTATE[42000]解决
    Laravel:php artisan key:generate三种报错解决方案,修改默认PHP版本(宝塔面板)
    大型网站如何防止崩溃,解决高并发带来的问题
    PHP微信公众平台OAuth2.0网页授权,获取用户信息代码类封装demo(二)
    iOS开发 ReactiveCocoa入门教程 第二部分
  • 原文地址:https://www.cnblogs.com/Qyhg/p/14071728.html
Copyright © 2011-2022 走看看