Skip to main content

01.模型和ORM

1.ORM是什么?

ORM(Object Relation Mapping)对象映射关系。ORM一种将数据表抽象成对象的编程思想。简单点,可以当成一个数据表对应一个对象,对数据的操作不再看成是对数据表的操作,表与表之间的关系也不再是外键和内键的关系,而是对象与对象的作用关系。
TP5.0的ORM主要应用在模型中对数据库的操作中。

2. 关联模型

2.1 相对关联模型(内嵌关联模型)

1,主模型

<?php
namespace app\api\model;
use think\Model;
class Banner extends Model
{
public function bannerItem()
{
///多对多Banner模型关联BannerItem模型
return $this->hasMany("BannerItem","banner_id","id");
}
}

2, 关联模型

<?php
namespace app\api\model;
use think\Model;
class BannerItem extends Model
{
public function Image() {
//相对关联
return $this->BelongsTo("Image","img_id","id");
}
}

3,Images模型

<?php
namespace app\api\model;
use think\Model;
class Image extends Model
{

}

4,调用

<?php
namespace app\api\controller\v1;
use think\Controller;
use app\api\model\Banner as BannerModel;
class Banner extends Controller
{
public function getBanner($id)
{
//内嵌关联模型调用
$result = BannerModel::get($id,['BannerItem','BannerItem.Image' ]);
return json($result);
}
}

5,输出

{
"id": 1,
"name": "首页置顶",
"description": "首页轮播图",
"delete_time": null,
"update_time": "1970-01-01 08:00:00",
"banner_item": [
{
"id": 1,
"img_id": 65,
"key_word": "6",
"type": 1,
"delete_time": null,
"banner_id": 1,
"update_time": "1970-01-01 08:00:00",
"image": {
"id": 65,
"url": "/banner-4a.png",
"from": 1,
"delete_time": null,
"update_time": "1970-01-01 08:00:00"
}
},
{
"id": 2,
"img_id": 2,
"key_word": "25",
"type": 1,
"delete_time": null,
"banner_id": 1,
"update_time": "1970-01-01 08:00:00",
"image": {
"id": 2,
"url": "/banner-2a.png",
"from": 1,
"delete_time": null,
"update_time": "1970-01-01 08:00:00"
}
},
{
"id": 3,
"img_id": 3,
"key_word": "11",
"type": 1,
"delete_time": null,
"banner_id": 1,
"update_time": "1970-01-01 08:00:00",
"image": {
"id": 3,
"url": "/banner-3a.png",
"from": 1,
"delete_time": null,
"update_time": "1970-01-01 08:00:00"
}
},
{
"id": 5,
"img_id": 1,
"key_word": "10",
"type": 1,
"delete_time": null,
"banner_id": 1,
"update_time": "1970-01-01 08:00:00",
"image": {
"id": 1,
"url": "/banner-1a.png",
"from": 1,
"delete_time": null,
"update_time": "1970-01-01 08:00:00"
}
}
]
}