As a beginner in Typeorm, I have been working on a web page with Angular + Typeorm for the past few weeks. Despite my efforts to resolve this issue by myself and researching previously asked questions here on Stackoverflow, I have unfortunately been unable to make any progress recently. So, here's my question: I have two entities, each having a many-to-many relationship between them.
@Entity("noticias")
@Unique(["idnoticias"])
export class Noticias extends BaseEntity{
@PrimaryGeneratedColumn()
idnoticias: number;
@Column({type: "text", nullable: true})
tituloNoticia: string;
@Column({type: "text", nullable: false})
contenidoNoticia: string;
@Column({type: "text", nullable: true})
usuario: string;
@Column({type: "date", nullable: false})
fechaCreacion: Date;
@Column({type: "date", nullable: true})
fechaPublicacion: Date;
@ManyToMany(type => Etiquetas, etiqueta => etiqueta.noticias)
@JoinTable()
etiquetas: Etiquetas[];
}
@Entity("etiquetas")
@Unique(['idetiquetas'])
export class Etiquetas extends BaseEntity {
@PrimaryGeneratedColumn()
idetiquetas: number;
@Column({type: "text", nullable: false})
nombre: string;
@ManyToMany(type => Noticias, noticia => noticia.etiquetas)
@JoinTable()
noticias: Noticias[];
}
In addition, I have a post function that receives a 'Noticias' entity and saves it into the database.
static postNoticia = async (req: Request, res: Response)=>{
try {
const {
tituloNoticia,
contenidoNoticia,
usuario,
fechaCreacion,
fechaPublicacion,
etiquetas
} = req.body;
const noticia = Noticias.create({
tituloNoticia: tituloNoticia,
contenidoNoticia: contenidoNoticia,
usuario: usuario,
fechaCreacion: fechaCreacion,
fechaPublicacion: fechaPublicacion,
etiquetas: etiquetas,
});
await noticia.save();
return res.json(noticia);
} catch(e) {
console.log(e);
res.status(500).json({message: 'Error'});
}
};
My goal is simple: when the 'postNoticia' function receives a request with an array of 'Etiquetas' objects, instead of saving all objects again in the database, I want it to check if they already exist, load them, and instantiate the many-to-many relation with the new 'Noticias' object to avoid duplicate entries. I initially tried using cascades, but it just inserts all 'Etiquetas' objects again, which is not what I want. The objective is to establish relations with existing IDs without inserting duplicates. I have read the official documentation, but the example provided does not address this issue clearly. I believe it should search for existing objects in the database, retrieve their IDs, and create the relation accordingly. However, despite my efforts, I haven't been able to make it work. If this question has already been answered elsewhere, please let me know so I can close it. Thank you in advance.