在 Nest.js 中执行 SQL 查询通常涉及使用 TypeORM 或 Sequelize 这样的 ORM(对象-关系映射)库。这些库使得在 Nest.js 应用程序中连接和操作 SQL 数据库变得更加简单和直观。
以下是一个使用 TypeORM 在 Nest.js 中执行 SQL 查询的示例代码:
首先,确保你已经在项目中安装了 TypeORM:
在user模块中的entites中;user.entity.ts中有如下代码:
import { Column, Entity, PrimaryGeneratedColumn } from "typeorm";
@Entity()
export class User {@PrimaryGeneratedColumn()id: number@Column()username: string@Column()password: string
}
在user模块中的service中;user.service.ts中有如下代码:
import { Injectable } from '@nestjs/common';
import { UserDto } from './dto/create-user.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from './entities/user.entity';
import { Repository } from 'typeorm';
@Injectable()
export class UserService {constructor(@InjectRepository(User) private readonly user: Repository<User>) { }async login(userDto: UserDto) {const userInfo = await this.user.findOne({where: {username: userDto.username,password: userDto.password,},})return userInfo;}async register(userDto: UserDto) {const existingUser = await this.user.findOne({where: {username: userDto.username,},});if (existingUser) {return '用户名已存在';}const data = new User();data.username = userDto.username;data.password = userDto.password;return this.user.save(data);}
}
很明显没有使用sql语句,但是也完成了sql操作;
在另一个项目中使用的是
user模块中的user.model.ts中代码如下:
import { Column, Model, Table } from 'sequelize-typescript';@Table
export class User extends Model<User> {@Columnusername: string;@Columnpassword: string;@Columnavatar: string;
}
在user.service.ts中代码如下:
import { Injectable } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { InjectModel } from '@nestjs/sequelize';
import { User } from './model/user.model';
@Injectable()
export class UserService {constructor(@InjectModel(User) private userModel: typeof User,) {}async create(createUserDto: CreateUserDto) {let res = await this.userModel.build({...createUserDto})await res.save()return res}async findAll() {let res = await this.userModel.findAll()return res}async find(createUserDto: CreateUserDto) {let res = await this.userModel.findOne({where: {...createUserDto}})return res}async findOne(username: string) {let res = await this.userModel.findOne({where: {username}})return res !== null ? res : null}async uploadAvatar(username: string, avatar: string) {let res = await this.userModel.update({avatar}, {where: {username: username}})return {code: '200',msg: "上传成功",data: res}}async hasAvatar(username: string) {let res = await this.userModel.findOne({where: {username: username}})return res.avatar !== null}
}