🦄 2024 独立开发者训练营,一起创业!(早鸟优惠在1天后结束)查看介绍 / 立即报名 →

NNC D13:评论

D13 的任务是在应用里添加一个评论功能,评论也是应用里的一种实体,围绕这种实体可以去创建一个评论模块。

src/modules/comment/comment.entity.ts

import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn, ManyToOne } from 'typeorm';
import { Post } from '../post/post.entity';
import { User } from '../user/user.entity';

@Entity()
export class Comment {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ nullable: true })
  title: string;

  @Column()
  body: string;

  @CreateDateColumn()
  created: Date;

  @UpdateDateColumn()
  updated: Date;

  @ManyToOne(type => Post, post => post.comments, { nullable: false })
  post: Post;

  @ManyToOne(type => User, user => user.comments, { nullable: false })
  user: User;
}

我们尽量保持实体的定义简单,你可以根据自己的需求去添加其它需要的字段。注意在定义评论实体的时候定义了评论与文章,还有评论与用户之间的关系。一条评论只能属于一个内容,评论也只能有一个作者,所以用 @ManyToOne 来定义它们的关系。

处理评论发布请求用的方法:

src/modules/comment/comment.service.ts

  async storePostComment(id: number, user: User, data: CommentDto) {
    return await this.commentRepository.save({
      user,
      ...data,
      post: { id }
    })
  }

存储评论的时候需要知道评论所属的内容的 id 号,还有评论的作者是谁。给 Repository 的 save 方法提供的数据里面,user 与 post 这两个属性是我们在评论实体上定义的用户与内容关系的名字。

处理显示文章内容评论用的方法:

 async showPostComments(id: number) {
    return await this.commentRepository
      .createQueryBuilder('comment')
      .leftJoinAndSelect('comment.user', 'user')
      .leftJoinAndSelect('comment.post', 'post')
      .where('post.id = :id', { id })
      .getMany();
  }

处理显示用户评论列表的方法:

  async showUserComments(id: number) {
    return await this.commentRepository
      .createQueryBuilder('comment')
      .leftJoinAndSelect('comment.user', 'user')
      .leftJoinAndSelect('comment.post', 'post')
      .where('user.id = :id', { id })
      .getMany();
  }
微信好友

用微信扫描二维码,
加我好友。

微信公众号

用微信扫描二维码,
订阅宁皓网公众号。

240746680

用 QQ 扫描二维码,
加入宁皓网 QQ 群。

统计

14696
分钟
0
你学会了
0%
完成

社会化网络

关于

微信订阅号

扫描微信二维码关注宁皓网,每天进步一点