I'm going to simplify this, I have 3 entities.
//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;
}
So I have my user created, no songs or lyrics, but I have his id
user = {
UserId = '0433bd30-e21d-4581-8906-a5ee1a5b23d4',
Songs = [],
Lyrics = []
}
When I am creating a song I need my UserId and my lyric or lyrics
const song= this.repository.create({
userId,
Lyrics
})
I was trying this on my 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'
},
]
So i try to save my song
await this.repository.save(cancion)
All it's ok, but my Lyric entity only get the SongId and UserId is empty
So what Im doing righ now is make two saves, but idw if I can get this doing only one
That's what Im doing right now
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 )
I think there is a bad configuration with the entities, when I save a song everything works correctly, but my lyrics entity only takes SongId and UserId is empty
What do u think about it?
Part #1
and
There is no property
songIdonSong. There is a propertySongId.Part #2
Check better this part:
If
lyriccomes with empty/undefinedSongId, it will get overwritten, because it comes afterSongId. BesidesSongIdandsongIdare different props.Part #3
What's the use of defining reverse relationship to
LyricsonUser? LeaveuseronLyricsonly, and you'll still be able to fetch lyrics for given user. And there will be one entity to save. Similarly, onlyLyricsneed relation toSong.Songdoesn't need to have reverse relation with lyrics. If I'm getting your struggle well, that should save you a loooooot of hassle. You'll only updateLyrics, and still be able to fetch lyrics for song, songs for one lyrics, user for lyrics, and lyrics for user.Besides, that's what TypeORM does, I guess?
Part #4
Switch to MikroORM :D