nestjs如何使用typeorm
默认你有点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); } }
nest使用typeorm简单例子
Nav.ts
import { Entity,PrimaryGeneratedColumn,Column, CreateDateColumn,UpdateDateColumn } from "typeorm"; @Entity({name:'Nav'}) export class Nav { @PrimaryGeneratedColumn() id:number; @Column() title:string; @Column({default:0}) order:number; @Column({nullable:true}) parentNavigation:number; @Column({nullable:true}) icon:string; @Column({default:true}) isVisible:boolean }
nav.module.ts
import { Module } from '@nestjs/common'; import { NavController } from './nav.controller'; import { NavService } from './nav.service'; import { TypeOrmModule } from '@nestjs/typeorm'; import { Nav } from 'src/typeorm/entities/Nav'; @Module({ imports:[TypeOrmModule.forFeature([Nav])], controllers: [NavController], providers: [NavService] }) export class NavModule { }
nav.service.ts
import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Nav } from 'src/typeorm/entities/Nav'; import { Repository } from 'typeorm'; @Injectable() export class NavService { constructor(@InjectRepository(Nav) private navRepository:Repository<Nav>){} findNav(){ return this.navRepository.find() } }
nav.controller.ts
import { Controller,Get } from '@nestjs/common'; import { NavService } from './nav.service'; @Controller('nav') export class NavController { constructor(private navService:NavService){} @Get() async getNav(){ return this.navService.findNav() } }
不要忘记这里