新建一个模型类
applicationapimodelBanner.php
class Banner
{
public static function getBannerByID($id)
{
//
}
}
原生方法
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;
}
}
查看返回结果
如已关闭了tp5默认记录日志,则需手动记录
publicindex.php
require __DIR__ . '/../thinkphp/start.php';
// 放置在加载框架引导文件之后
hinkLog::init([
'type' => 'File',
'path' => LOG_PATH,
'level' => ['sql']
]);
查看效果
调用一次接口(执行一次查询)后
ORM与模型
Object Relation Mapping 对象关系映射
以操作一个对象的方式来获取数据
模型是根据功能划分的,不单单是一个类一个表,其返回的结果可能是很多表共同生成的
继承tp5自带的model类
applicationapimodelBanner.php
namespace appapimodel;
use thinkModel;
class Banner extends Model
{
}
使用
applicationapicontrollerv1Banner.php
<?php
namespace appapicontrollerv1;
use appapivalidateIDMustBePositiveInt;
use appapimodelBanner as BannerModel;
use applibexceptionBannerMissException;
class Banner
{
public function getBanner($id)
{
(new IDMustBePositiveInt())->goCheck();
$banner = BannerModel::get($id);
if (!$banner) {
throw new BannerMissException();
}
// 观察继承了BannerModel的返回结果,返回了个模型对象,而不是像Db一样的数组
// 可直接返回不再序列化处理,tp5会自动将模型对象序列化
return $banner;
}
}
再在config.php配置中更改默认输出类型可返回正常结果
applicationconfig.php
return [
//...
'default_return_type' => 'json',
//...
]
查看结果
tp5默认表名和类名一致,如不是需要额外处理,例如下面的Banner模型关联的表就是cateory表
class Banner extends Model
{
protected $table = 'cateory'
//...
}