預設你有點nestjs基礎
第一步安裝
npm add @nestjs/typeorm typeorm mysql2
第二步
imports: [TypeOrmModule.forRoot({ type:'mysql', host:'', port:3306, username:'', password:'', database:'', entities:[User,User1], synchronize:true }), UsersModule, Users1Module],
UsersModule是我加的模組,他自己加上去的
第三步,建立表
import { Column,Entity,PrimaryGeneratedColumn } from "typeorm"; @Entity({name:'users'}) export class User{ @PrimaryGeneratedColumn({type:'bigint'}) id:number @Column({unique:true}) username:string; @Column() password:string; @Column() createAt:Date; @Column({nullable:true}) authStrategy:string }
第四步,使用
第二部分
如何在server使用
service.ts
import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { User } from 'src/typeorm/entities/User'; import { CreateUserParams } from 'src/utils/types'; import { Repository } from 'typeorm'; @Injectable() export class UsersService { constructor( @InjectRepository(User) private userRepository:Repository<User>, ){} findUsers(){ return this.userRepository.find() } createUser(userDetails:CreateUserParams){ const newUser=this.userRepository.create({...userDetails,createAt:new Date()}) return this.userRepository.save(newUser); } }