我要简化这个,我有 3 个实体。
//1er entity
@Entity()
export class Song{
@PrimaryGeneratedColumn('uuid')
SongId: string;
@Column()//this is a UserId
Owner: string;
@OneToMany( type => Lyric, lyric => lyric.Song, {
cascade: true
})//I supposed different versions
Lyrics: Lyric[];
}
//2nd entity
@Entity()
export class Usuario {
@PrimaryGeneratedColumn('uuid')
UsuarioId: string;
@ManyToMany(type => Song, song => Song.songId)
@JoinTable()
Songs: Song[] | null;
@OneToMany( type => Lyric, lyric => lyric.User)
Lyrics: Lyric[] | null;
//3er entity
@Entity()
export class Lyric{
@PrimaryGeneratedColumn('uuid')
LyricId: string;
@Colum()
lyric: string;
@ManyToOne( type => User, user => user.Lyrics)
User: User;
@ManyToOne( type => Song, song => song.Lyrics)
Song: Song;
}
所以我创建了我的用户,没有歌曲或歌词,但我有他的ID
user = {
UserId = '0433bd30-e21d-4581-8906-a5ee1a5b23d4',
Songs = [],
Lyrics = []
}
当我创建歌曲时,我需要我的 UserId 和我的歌词
const song= this.repository.create({
userId,
Lyrics
})
我在我的歌词中尝试过这个
Lyrics = [
{
UserId: userId,
Lyric: 'hello, hello, this is the lyric, etc etc'
},
{
UserId: userId,
Lyric: 'hello again, hello, this is the lyric, etc etc'
},
]
所以我尝试保存我的歌曲
await this.repository.save(cancion)
一切都好,但我的 Lyric 实体只获取 SongId,UserId 为空
所以我现在正在做的是进行两次保存,但是如果我能做到这一点,我只能做一次
这就是我现在正在做的事情
Lyrics.forEach(async lyric=> {
const newLyricWithUserAndSong : CreateLyricDto = {
SongId: song.songId,// this is my first save await this.repository.save(song)
...lytic
}
await this.lyricService.create(newLyricWithUserAndSong )
我认为实体配置有问题,当我保存歌曲时一切正常,但我的歌词实体只接受 SongId 而 UserId 为空
你对此有何看法?
第#1部分
@PrimaryGeneratedColumn('uuid')
SongId: string;
和
@ManyToMany(type => Song, song => Song.songId)
@JoinTable()
Songs: Song[] | null;
songId
上没有属性 Song
。有一个属性SongId
。
第 2 部分
更好地检查这部分:
const newLyricWithUserAndSong : CreateLyricDto = {
SongId: song.songId,// this is my first save await this.repository.save(song)
...lyric
}
如果
lyric
带有空/未定义的SongId
,它将被覆盖,因为它出现在SongId
之后。另外SongId
和songId
是不同的道具。
第 3 部分
在
Lyrics
上定义与User
的反向关系有什么用?仅将 user
保留在 Lyrics
上,您仍然可以获取给定用户的歌词。并且将有一个实体需要拯救。同样,只有 Lyrics
需要与 Song
相关。 Song
不需要与歌词有反向关系。
如果我能很好地解决你的问题,那应该可以为你省去很多麻烦。您只需更新 Lyrics
,并且仍然能够获取歌曲的歌词、一首歌词的歌曲、歌词的用户以及用户的歌词。
此外,我猜这就是 TypeORM 的作用?
第 4 部分
切换到 MikroORM :D