我正在尝试以一对多关系保存 Nestjs 项目中的对象数组。
前端给了我这样的东西来使用:
[
{
"actor":"actorname",
"role":"actorrole"
},
{
"actor":"actorname2",
"role":"actorrole2"
}
]
为了保存所有这些,我创建了一个电影实体和一个演员实体,如下所示:
演员.实体.ts
//imports
@Entity()
export class Actor {
@PrimaryGeneratedColumn()
id: number;
@ManyToOne(() => Movie, (movie) => movie.actors)
movieId: number;
@Column()
role: string;
@Column()
actor: string;
}
电影.实体.ts
//imports
@Entity()
export class Movie {
@PrimaryGeneratedColumn()
id: number;
//more stuff
@OneToMany(() => Actor, (actor) => actor.movieId)
actors: Actor[];
}
现在的问题是,我的前端将 JSON 数据作为整个字符串返回,所以我必须首先
JSON.parse()
并在我的 dto 中接受它,如下所示:
//imports
export class CreateMovieDto {
actorsArray: string;
}
现在我的问题是保存 json 数据
//imports
@EntityRepository(Movie)
export class MoviesRepository extends Repository<Movie> {
async createMovie(
createMovieDto: CreateMovieDto,
fileName: string,
filePath: string,
) {
const movie = this.create(createMovieDto);
let actorsArray = JSON.parse(createMovieDto.actorsArray);
//how do i save it now together with the movie?
try {
//await this.save(movie); disabled for now
return movie;
} catch (error) {
if ((error.code = 'ER_DUP_ENTRY')) {
console.log(error);
throw new ConflictException('Movie already exists');
} else {
console.log(error);
throw new InternalServerErrorException();
}
}
}
你应该做这样的事情
//现在如何将其与电影一起保存?
const actorsEntities = await Promise.all( actorsArray.map(async (actor) => {
const actorEntity = new Actor(actor);
// Save the image entity to the database
await this.actorsRepository.save(actorEntity);
return actorEntity;
}),
);
movie.actors = actorsEntities;
);
this.save(movie);