「php」TP5.0学习笔记-模型和ORM

1.ORM是什么?跟TP5.0模型有什么关系?

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

2. 关联模型

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

1,主模型

1
2
3
4
5
6
7
8
9
10
11
<?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, 关联模型

1
2
3
4
5
6
7
8
9
10
<?php
namespace app\api\model;
use think\Model;
class BannerItem extends Model
{
public function Image() {
//相对关联
return $this->BelongsTo("Image","img_id","id");
}
}

3,Images模型

1
2
3
4
5
6
7
<?php
namespace app\api\model;
use think\Model;
class Image extends Model
{

}

4,调用

1
2
3
4
5
6
7
8
9
10
11
12
13
<?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,输出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
{
"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"
}
}
]
}

坚持原创技术分享,您的支持将鼓励我继续创作!
0%