Каким образом в typeorm использовать вложенные запросы в relationship?
Каким образом в typeorm посчитать количество count()Find Options В sql вроде костыльно реализовал но в NestJs (
findAll() {
return this.postsRepository.find({
//relations: ['user', 'images', 'comments', 'likes', 'shares'],
relations: ['user', 'images'],
});
}
@Entity()
export class Post {
@PrimaryGeneratedColumn()
id: number;
@Column()
title: string;
@Column({ type: 'text' })
post_text: string;
@CreateDateColumn()
created_at: Date;
@UpdateDateColumn()
updated_at: Date;
@ManyToOne(() => User, (user) => user.post, { cascade: true })
user: User[];
@OneToMany(() => Image, (image) => image.post, { cascade: true })
images: Image[];
@OneToMany(() => Comment, (comment) => comment.post, { cascade: true })
comments: Comment[];
@OneToMany(() => Like, (like) => like.post, { cascade: true })
likes: Like[];
@OneToMany(() => Share, (share) => share.post, { cascade: true })
shares: Share[];
}
SELECT
*,
(SELECT
COUNT(comment.postId)
FROM
comment
WHERE
post.id = comment.postId) AS count_comments,
(SELECT
COUNT(likes.postId)
FROM
likes
WHERE
post.id = likes.postId) AS count_likes,
(SELECT
COUNT(share.postId)
FROM
share
WHERE
post.id = share.postId) AS count_shares
FROM
post
LEFT JOIN
user ON post.userId = user.id
LEFT JOIN
image ON post.id = image.postId
LEFT JOIN
comment ON post.id = comment.postId;
json api
[
{
"id": 1,
"title": "title1",
"post_text": "text1",
"created_at": "2021-10-16T13:34:14.247Z",
"updated_at": "2021-10-16T13:34:14.247Z",
"user": {
"id": 1,
"firstName": "James1",
"lastName": "Spiegel1",
"avatar": "default"
},
"images": [
{
"id": 2,
"image_path": "default1"
},
{
"id": 1,
"image_path": "default1"
}
]
},
{
"id": 2,
"title": "title1",
"post_text": "text1",
"created_at": "2021-10-16T13:34:15.033Z",
"updated_at": "2021-10-16T13:34:15.033Z",
"user": {
"id": 1,
"firstName": "James1",
"lastName": "Spiegel1",
"avatar": "default"
},
"images": [
{
"id": 3,
"image_path": "default1"
}
]
},
{
"id": 3,
"title": "title1",
"post_text": "text1",
"created_at": "2021-10-16T13:34:19.087Z",
"updated_at": "2021-10-16T13:34:19.087Z",
"user": {
"id": 2,
"firstName": "James1",
"lastName": "Spiegel1",
"avatar": "default"
},
"images": []
}
]
