【问题标题】:How can i post a DTO that contain an array of entities?如何发布包含实体数组的 DTO?
【发布时间】:2021-04-12 17:31:09
【问题描述】:

我有几个关于 NestJS 和 TypeOrm 的问题。 首先,如何将字符串数组传递给 DTO?我试图只使用 :string[] 类型,但编译器给出了错误。 这是我的 Post 实体:

@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[];
}

第二个问题:我如何将每张照片(保持与帖子的连接)保存到存储库,发布到帖子存储库并通过添加绑定到他的新帖子来更新用户。 我试过这样的东西,但它显然不起作用。

    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});
  }

【问题讨论】:

  • 照片是否已经存入数据库?照片数组的内容是什么?你能分享照片实体吗?
  • @Youba,不,照片也是创建的。照片数组的内容将是字符串。字符串数组(网址)。我已经找到了解决方案,但不知道它有多正确:prnt.sc/wi6d1p
  • 检查我的答案

标签: nestjs typeorm


【解决方案1】:

您在这里错过的是在将照片与帖子绑定之前保存照片,这是一个示例:

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});
  }

【讨论】:

  • 谢谢。它对我有用,但图像的 postId 为空。如何在 Post 初始化之前将 post 对象传递给照片? (我的帖子实体有网址和帖子:PostEntity)
  • 可以分享照片实体吗?
  • prnt.sc/wi7619 抱歉链接。无法发送格式化代码。
  • 等等,一切正常。我使用 forEach 而不是 for (let ... of ..)。谢谢!
  • 祝你好运,下次尝试用要求的代码编辑你的帖子,最好是截图,
猜你喜欢
  • 1970-01-01
  • 2015-12-09
  • 1970-01-01
  • 1970-01-01
  • 2021-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-10
相关资源
最近更新 更多