You need to enable JavaScript to run this app. Nest.js中TypeORM+PostgreSQL实现同ID多行存储数组数据的方案
优惠活动
大模型
产品
解决方案
定价
更多

Nest.js中TypeORM+PostgreSQL实现同ID多行存储数组数据的方案

实现方案

1. 定义核心实体

通过User、Book、Like三个实体,用一对多/多对一关系实现用户与书籍的关联存储,同一个userId可对应多条不同bookId的Like记录。

User 实体

import { Entity, PrimaryGeneratedColumn, Column, OneToMany } from 'typeorm';
import { Like } from './like.entity';

@Entity()
export class User {
  @PrimaryGeneratedColumn('uuid') // 可替换为自增int,根据业务选择
  id: string;

  @Column()
  username: string;

  // 一个用户对应多条Like记录
  @OneToMany(() => Like, like => like.user, { cascade: true })
  likes: Like[];
}

Book 实体

import { Entity, PrimaryGeneratedColumn, Column, OneToMany } from 'typeorm';
import { Like } from './like.entity';

@Entity()
export class Book {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column()
  title: string;

  // 一本书被多个用户喜欢,对应多条Like记录
  @OneToMany(() => Like, like => like.book)
  likedBy: Like[];
}

Like 实体(核心关联表)

专门存储用户与书籍的喜欢关系,支持同一用户关联多本书:

import { Entity, PrimaryGeneratedColumn, ManyToOne, Column, JoinColumn } from 'typeorm';
import { User } from './user.entity';
import { Book } from './book.entity';

@Entity()
export class Like {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  // 多对一关联User
  @ManyToOne(() => User, user => user.likes, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'userId' })
  user: User;

  @Column()
  userId: string; // 显式存储userId,简化查询操作

  // 多对一关联Book
  @ManyToOne(() => Book, book => book.likedBy, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'bookId' })
  book: Book;

  @Column()
  bookId: string; // 显式存储bookId,简化查询操作

  // 可选:添加喜欢时间字段
  @Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' })
  likedAt: Date;
}

2. 配置TypeORM与PostgreSQL连接

在app.module.ts中完成数据库连接配置,确保实体被正确加载:

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { User } from './entities/user.entity';
import { Book } from './entities/book.entity';
import { Like } from './entities/like.entity';
import { LikeModule } from './like/like.module';

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'postgres',
      host: 'localhost',
      port: 5432,
      username: '你的数据库用户名',
      password: '你的数据库密码',
      database: '你的数据库名',
      entities: [User, Book, Like],
      synchronize: true, // 开发环境可用,生产环境建议关闭,改用数据库迁移
    }),
    LikeModule,
  ],
})
export class AppModule {}

3. 实现业务逻辑(LikeService)

封装用户喜欢书籍的核心操作,包括添加、查询、取消喜欢:

import { Injectable, NotFoundException, ConflictException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Like } from '../entities/like.entity';
import { User } from '../entities/user.entity';
import { Book } from '../entities/book.entity';

@Injectable()
export class LikeService {
  constructor(
    @InjectRepository(Like)
    private likeRepository: Repository<Like>,
    @InjectRepository(User)
    private userRepository: Repository<User>,
    @InjectRepository(Book)
    private bookRepository: Repository<Book>,
  ) {}

  // 用户添加喜欢书籍
  async addLike(userId: string, bookId: string): Promise<Like> {
    // 校验重复喜欢
    const existingLike = await this.likeRepository.findOne({
      where: { userId, bookId },
    });
    if (existingLike) {
      throw new ConflictException('已喜欢过这本书');
    }

    // 校验用户和书籍是否存在
    const user = await this.userRepository.findOneBy({ id: userId });
    if (!user) throw new NotFoundException('用户不存在');
    
    const book = await this.bookRepository.findOneBy({ id: bookId });
    if (!book) throw new NotFoundException('书籍不存在');

    const like = this.likeRepository.create({ user, book });
    return this.likeRepository.save(like);
  }

  // 查询用户喜欢的所有书籍
  async getUserLikes(userId: string): Promise<Like[]> {
    return this.likeRepository.find({
      where: { userId },
      relations: ['book'], // 关联查询书籍详情
    });
  }

  // 取消喜欢书籍
  async removeLike(userId: string, bookId: string): Promise<void> {
    const result = await this.likeRepository.delete({ userId, bookId });
    if (result.affected === 0) {
      throw new NotFoundException('未找到该喜欢记录');
    }
  }
}

4. 创建API控制器(LikeController)

对外提供HTTP接口,供前端调用:

import { Controller, Post, Delete, Get, Param, HttpCode, HttpStatus } from '@nestjs/common';
import { LikeService } from './like.service';

@Controller('likes')
export class LikeController {
  constructor(private readonly likeService: LikeService) {}

  @Post(':userId/book/:bookId')
  async addLike(@Param('userId') userId: string, @Param('bookId') bookId: string) {
    return this.likeService.addLike(userId, bookId);
  }

  @Get(':userId')
  async getUserLikes(@Param('userId') userId: string) {
    return this.likeService.getUserLikes(userId);
  }

  @Delete(':userId/book/:bookId')
  @HttpCode(HttpStatus.NO_CONTENT)
  async removeLike(@Param('userId') userId: string, @Param('bookId') bookId: string) {
    await this.likeService.removeLike(userId, bookId);
  }
}

关键说明

  • 关联逻辑:通过Like实体作为中间表,用@ManyToOne分别关联User和Book,反向用@OneToMany关联,自然支持同一用户对应多条不同书籍的喜欢记录。
  • 数据一致性:设置onDelete: 'CASCADE',当用户或书籍被删除时,对应的Like记录会自动删除,避免脏数据。
  • 显式外键:在Like实体中定义userId和bookId字段,无需每次关联查询实体即可直接通过这两个字段进行条件筛选,提升查询效率。

内容的提问来源于stack exchange,提问作者Dheeraj Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 04:40:29