【发布时间】:2021-04-04 22:06:45
【问题描述】:
我有 PublicationsEntity 与 LikesEntity 的 OneToMany 关系,我正在尝试按喜欢对我的出版物进行排序,并返回所有喜欢与喜欢关联的用户的喜欢,以及所有 cmet 以在前端显示它们
@Entity('publications')
export class PublicationsEntity {
@PrimaryGeneratedColumn()
id: number;
@Column({ type: 'longtext' })
publication: string;
@ManyToOne(type => UsersEntity, users => users.publications, {
onDelete: "CASCADE" })
user: UsersEntity;
@OneToMany(type => CommentsEntity, comments =>
comments.publication, { onDelete: "CASCADE" })
comments: CommentsEntity[];
@OneToMany(type => LikesEntity, likes => likes.publication, { onDelete: "CASCADE" })
likes: LikesEntity[];
}
有一个我喜欢的实体包含用户,我试图在排序后的出版物中返回每个喜欢的用户:
@Entity('likes')
export class LikesEntity {
@PrimaryGeneratedColumn()
id: number;
@Column()
like: number;
@ManyToOne(type => UsersEntity, user => user.likes, { eager: true })
user: UsersEntity;
@ManyToOne(type => PublicationsEntity, publication => publication.likes)
publication: PublicationsEntity;
}
我的用户实体:
@Entity('users')
export class UsersEntity {
@PrimaryGeneratedColumn()
id: number;
@Column({ nullable: true })
userName: string;
@OneToMany(type => PublicationsEntity, publications =>
publications.user, { onDelete: "CASCADE" })
publications: PublicationsEntity[];
@Column()
email: string;
@Column({ select: false })
password: string;
@OneToMany(type => CommentsEntity, comment => comment.user, { onDelete: "CASCADE" })
comments: CommentsEntity[];
@OneToMany(type => LikesEntity, like => like.user, { onDelete: "CASCADE" })
likes: LikesEntity[];
@OneToMany(type => PublicationsEntity, publications => publications.user, { onDelete: "CASCADE" })
publications: PublicationsEntity[];
@CreateDateColumn({ type: "timestamp", default: () => "CURRENT_TIMESTAMP(6)" })
createdAt: Date;
@UpdateDateColumn({ type: "timestamp", default: () => "CURRENT_TIMESTAMP(6)", onUpdate: "CURRENT_TIMESTAMP(6)" })
updatedAt: Date;
}
还有我的 PublicationsService
async getPublications() {
return await getConnection()
.createQueryBuilder(PublicationsEntity, 'publications')
.leftJoinAndSelect('publications.likes', 'likes')
.leftJoinAndSelect('publications.user', 'user')
.leftJoinAndSelect('publications.comments', 'comments')
.leftJoinAndSelect('comments.children', 'children')
//.orderBy()
.getMany()
}
我点赞表上的一些数据:https://i.stack.imgur.com/wJ0l5.png
【问题讨论】: