typeorm查询两个没有关联关系的实体

Post实体

@Entity({ name: 'post', schema: 'public' })
export class Post {
    @PrimaryGeneratedColumn()
    id: number;

    @Column({ nullable: false })
    title: string;

    @Column({
        type: 'text', nullable: false
    })
    content: string;

}

PostExtend 实体

在post实体中设置postId存放post主键id

 1 @Entity({ name: 'postExtend', schema: 'public' })
 2 export class PostExtend {
 3     @PrimaryGeneratedColumn()
 4     id: number;
 5 
 6     @Column({ nullable: false })
 7     postId: number;
 8 
 9     @Column({ nullable: true })
10     likeCount: number;
11 
12     @Column({ nullable: true })
13     readCount: number;
14 
15     @Column({ nullable: true })
16     forwardCount: number;
17 
18 }

 Post和PostExtend中没有设置关联关系,所以我们并不能在find option中关联两个实体进行连表查询。

但是可以用queryBuilder 

1 const posts = await getConnection()
2             .createQueryBuilder(Post, 'post')
3             .leftJoinAndSelect(PostExtend, 'postExtend', 'post.id=postExtend.postId')
4             .getManyAndCount()
5         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() 

1 @Get('all')
2     public async getPosts(@Query() query: any) {
3         const posts = await getConnection()
4             .createQueryBuilder(Post, 'post')
5             .leftJoinAndMapOne('post.postExtend',PostExtend, 'postExtend', 'post.id=postExtend.postId')
6             .getManyAndCount()
7         return posts;
8     }

上面代码的查询结果如下:

 1 [
 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,这样的结果清晰明了。

猜你喜欢

转载自www.cnblogs.com/zzk96/p/11397223.html