全栈微信小程序商城 学习笔记之七 数据库访问

原生方法

新建路由
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
{
    //
}
原文地址:https://www.cnblogs.com/Qyhg/p/14071728.html