注意:orm框架中,尽量不要加外键关联
弱弱的问一下
你们觉得typeorm好用嘛?为啥我觉得挺麻烦的啊?联查必须要给定一个关系,也就是说必须有外键,而且设置起来必须有manytoone和onetomany,而且储存的时候也必须按照他的一套来,而且manytoone的关联表竟然不返回主表的id,还要自己再指定一个比如说user_id的字段自己保存了,才能返回,他自己生成的userId并不返回。而且他的tree实体,看起来挺好的,但是用起来,真是难用,因为没法指定where条件啊。还是我不会用啊?就问问大家所有的orm框架都这么难搞嘛?我已经没写过sql很多年了。就拿一个查tree模型部门结构来说,我是自己写的先查根,再遍历根查孩子,这样子递归,可是这样子就有点拉跨,多查了很多次数据库,这样算法复杂度一下子上去了,部门少还没事。我就很郁闷,想知道大家都是怎么用orm框架的啊
1、定义两个实体
Dictionary_type实体
//定义Dictionary_type实体,字典类型
@EntityModel()
export class Dictionary_type {
@PrimaryGeneratedColumn("uuid")
id: string;
@Column({
comment: "编码",nullable: true,})
code: string;
@Column({
comment: "状态", nullable: true,default:1})
state: number;
@Column({
comment: "字典类型名称", nullable: true})
text: string;
@CreateDateColumn()
creatDate: string;
@UpdateDateColumn()
updateDate: string;
}
Dictionary_item 实体
在实体中设置type_id存放Dictionary_type主键id
@EntityModel()
export class Dictionary_item {
@PrimaryGeneratedColumn("uuid")
id: string;
@Column({
comment: "序号",nullable: true,})
sort: number;
@Column({
comment: "字典类型", nullable: true,})
type_id: string;
@Column({
comment: "字典类型值", nullable: true})
value: number;
@Column({
comment: "字典类型内容", nullable: true})
text: string;
@CreateDateColumn()
creatDate: string;
@UpdateDateColumn()
updateDate: string;
}
Post和PostExtend中没有设置关联关系,所以我们并不能在find option中关联两个实体进行连表查询。
但是可以用queryBuilder
const posts = await getConnection()
.createQueryBuilder(Post, 'post')
.leftJoinAndSelect(PostExtend, 'postExtend', 'post.id=postExtend.postId')
.getManyAndCount()
return posts;
查询结果:
[
[
{
"id": 1,
"title": "北京申奥成功",
"content": "2003年奥林匹克运动会将在北京举行,北京欢迎你!"
}
],
1
]
上面的查询结果中并没有PostExtend的数据,这是因为不能确定两个实体之间的关联关系,所以无法确定查询结果的显示形式。
当然,也可以通过 getRawMany() 方法获取原生字段来获取PostExtend的信息,但是这样的查询结果显示并不友好。
1 const posts = await getConnection()
2 .createQueryBuilder(Post, 'post')
3 .leftJoinAndSelect(PostExtend, 'postExtend', 'post.id=postExtend.postId')
4 .getRawMany()
5 return posts;
结果:
1 [
2 {
3 "post_id": 1,
4 "post_title": "北京申奥成功",
5 "post_content": "2003年奥林匹克运动会将在北京举行,北京欢迎你!",
6 "postExtend_id": 1,
7 "postExtend_postId": 1,
8 "postExtend_likeCount": 999,
9 "postExtend_readCount": 10000,
10 "postExtend_forwardCount": 666
11 }
12 ]
如果想要将原生字段映射到属性,可以使用 leftJoinAndMapOne() ,如果时一对多还可以使用 leftJoinAndMapMany()
const posts = await getConnection()
.createQueryBuilder(Post, 'post')
.leftJoinAndMapOne('post.postExtend',PostExtend, 'postExtend', 'post.id=postExtend.postId')
.getManyAndCount()
return posts;
结果:
[
2 [
3 {
4 "id": 1,
5 "title": "北京申奥成功",
6 "content": "2003年奥林匹克运动会将在北京举行,北京欢迎你!",
7 "postExtend": {
8 "id": 1,
9 "postId": 1,
10 "likeCount": 999,
11 "readCount": 10000,
12 "forwardCount": 666
13 }
14 }
15 ],
16 1
17 ]
postExtend的数据被映射到post.postExtend,这样的结果清晰明了。