经过进一步测试,您可以使用find->与这些习俗的关系多对多的关系。对于嵌套关系,只需用点符号指定关系即可。
const user = await getManager()
.getRepository(Models.User)
.findOne({
where: { id },
relations: [
// you have to specify the join table first (following) to retrieve the columns in the join table
'following',
// then you use dotted notation to get the relation from the join table
'following.artist',
// another example of a deeply nested relation
'favourites',
'favourites.song',
'favourites.song.supportingArtists',
'favourites.song.supportingArtists.artist',
],
});
也可以将join与嵌套的leftJoinAndSelect一起使用,但这更繁琐。
const user = await getManager()
.getRepository(Models.User)
.findOne({
where: { id },
join: {
alias: 'user',
leftJoinAndSelect: {
following: 'user.following',
artists: 'following.artist',
},
},
});
以下是更新的实体
用户艺术家跟踪
@Entity('userArtistFollowing')
export class UserArtistFollowing {
@PrimaryColumn()
userId: string;
@PrimaryColumn()
artistId: string;
@ManyToOne(
() => User,
(user) => user.following
)
user!: User;
@ManyToOne(
() => Artist,
(artist) => artist.usersFollowing
)
artist!: Artist;
@CreateDateColumn()
createdAt!: Date;
@UpdateDateColumn()
updatedAt!: Date;
}
艺术家
@Entity('artist')
export class Artist {
@PrimaryGeneratedColumn('uuid')
id: string;
@OneToMany(
() => UserArtistFollowing,
(userArtistFollowing) => userArtistFollowing.artist
)
usersFollowing: UserArtistFollowing[];
}
使用者
@Entity('user')
export class User {
@PrimaryColumn()
id: string;
@OneToMany(
() => UserArtistFollowing,
(userArtistFollowing) => userArtistFollowing.user
)
following: UserArtistFollowing[];
}