我有几个关于 NestJS 和 TypeOrm 的问题。 首先,如何将字符串数组传递给DTO?我尝试只使用 :string[] 类型,但编译器给出错误。 这是我的帖子实体:
@Entity('posts')
export class Post {
@PrimaryGeneratedColumn()
id: number;
@ManyToOne(() => User, user => user.posts, { cascade: true })
author: number;
@Column({ type: 'timestamp' })
date: Date;
@Column()
text: string;
@Column({ default: 0 })
likes: number;
@OneToMany(() => Photo, photo => photo.post, { cascade: true })
photos: Photo[];
}
和CreatePostDto:
export class CreatePostDto {
authorId: number;
date: Date;
text?: string;
// photos?: string[];
}
第二个问题:我如何将每张照片保存到存储库(保持与帖子的连接),将帖子发布到帖子存储库并通过添加绑定(bind)到他的新帖子来更新用户。 我尝试过类似的方法,但显然行不通。
async create(createPostDto: CreatePostDto) {
const post = this.postsRepository.create(createPostDto);
const user = await this.usersRepository.findOne(createPostDto.authorId);
return this.postsRepository.save({author: user, date: createPostDto.date, text: createPostDto.text});
}
最佳答案
您在这里错过的是在将照片与帖子绑定(bind)之前保存照片,这是一个示例:
async create(createPostDto: CreatePostDto) {
let photos:Array<Photo> = [] ; array of type photo entity
for(let urlPhoto of createPostDto.photos)
{
let photo = await this.imageRepository.save({url : urlPhoto }); you must save the photos first
photos.push(photo);
}
const user = await this.usersRepository.findOne(createPostDto.authorId);
return this.postsRepository.save({author: user, date: createPostDto.date, text:
createPostDto.text,photos:photos});
}
关于nestjs - 如何发布包含实体数组的 DTO?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65604757/