返回

如何在NestJs中连接数据库进行联表查询和记录操作?

前端

简介

在上一篇文章中,我们实现了Post接口和对接口的基础操作。本篇主要讲的是和数据库连接,使用数据库联表查询和操作记录。使用数据库将数据记录,就是一个完整的后台服务了。

数据库连接

NestJs支持多种数据库,如MySQL、MongoDB和PostgreSQL。首先,我们需要在项目中安装相应的数据库驱动程序。

npm install mysql2

然后,在ormconfig.json文件中配置数据库连接信息。

{
  "type": "mysql",
  "host": "localhost",
  "port": 3306,
  "username": "root",
  "password": "root",
  "database": "nest_test",
  "entities": [
    "src/entity/*.ts"
  ],
  "synchronize": true
}

接下来,在app.module.ts文件中导入TypeOrmModule模块并配置数据库连接。

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'mysql',
      host: 'localhost',
      port: 3306,
      username: 'root',
      password: 'root',
      database: 'nest_test',
      entities: [
        __dirname + '/../**/*.entity{.ts,.js}',
      ],
      synchronize: true,
    }),
  ],
})
export class AppModule {}

联表查询

在NestJs中,我们可以使用TypeORM来进行联表查询。首先,我们需要在实体类中定义关联关系。

@Entity()
export class Post {

  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  title: string;

  @Column()
  content: string;

  @ManyToOne(() => Author, author => author.posts)
  author: Author;
}
@Entity()
export class Author {

  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @OneToMany(() => Post, post => post.author)
  posts: Post[];
}

然后,我们可以使用createQueryBuilder()方法来进行联表查询。

const posts = await this.postRepository.createQueryBuilder('post')
  .leftJoinAndSelect('post.author', 'author')
  .getMany();

记录操作

在NestJs中,我们可以使用TypeORM来进行记录操作。

// 新增记录
const post = new Post();
post.title = 'Hello World';
post.content = 'This is my first post.';
await this.postRepository.save(post);

// 更新记录
const post = await this.postRepository.findOne(1);
post.title = 'Hello World 2';
post.content = 'This is my second post.';
await this.postRepository.save(post);

// 删除记录
await this.postRepository.delete(1);

总结

在本文中,我们介绍了如何在NestJs中连接数据库,进行联表查询和记录操作。这些操作是构建后台服务的基础,希望对大家有所帮助。