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,這樣的結果清晰明了。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM