- Nest.js学习之路(17)-TypeORM(4)设定一对多/
- Nest.js学习之路(18)-TypeORM(5)设定多对多
- Nest.js学习之路(14)- TypeORM库(1)存取 i
- Nest.js学习之路(19)-TypeORM(6)Query
- Nest.js学习之路(23)-TypeORM(10) Embe
- Nest.js学习之路(22)-TypeORM(9) Relat
- Nest.js学习之路(21)-TypeORM(8) Relat
- Nest.js学习之路(20)-TypeORM(7)Query
- Nest.js学习之路(16)-typeorm(3)basic
- 在 Nest.js 中使用 MongoDB 与 TypeORM
关于TypeORM设定一对多/多对一参考官网教学
假设新增用户entitiy,使得一个平台有多个使用者,代码如下:
import {Entity, PrimaryGeneratedColumn, Column, ManyToOne, RelationId} from 'typeorm';
import { Platform } from './Platform';
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@Column()
age: number;
@ManyToOne( type => Platform, platform => platform.users, {
onDelete: 'NO ACTION',
})
plat: Platform;
@RelationId((user: User) => user.plat)
platId: number;
}
在platform entity上,新增users属性并设定@OneToMany()
import {Column, Entity, PrimaryGeneratedColumn, OneToMany} from 'typeorm';
import { User } from './User';
@Entity() // 指定table name
export class Platform {
// 每新增一个的時候id+1
@PrimaryGeneratedColumn()
id: number;
// @Column为对应的数据库列,或是传入Column Options物件
@Column()
platformname: string;
// 传入Column Options物件设定mapping的列位属性
@Column({
type: 'varchar',
length: 50,
default: '123',
})
title: string;
@Column()
url: string;
@Column({
default: true, // 给预设值
})
isActive: boolean;
@OneToMany( type => User, user => user.plat ) // type指定User, 第二個参数是function预设传入第一个参数的type,这边需要设定inverse屬性,user entity里的dep屬性,这个属性不会存到数据库
users: [];
}
在feature文件夹下新建user文件夹,然后在user文件夹下分别新建user.controller.ts,user.module.ts,user.service.ts,userDTO.ts四个文件,
userDTO.ts文件代码如下:
import { IsString, MaxLength, IsNumber } from 'class-validator';
export class UserDTO {
@IsString()
@MaxLength(100)
name: string;
@IsNumber()
age: number;
}
user.service.ts文件内容如下:
import { Injectable } from '@nestjs/common';
import { User } from 'shared/entity/User';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UserDTO } from './userDTO';
@Injectable()
export class UserService {
constructor(
@InjectRepository(User)
private readonly userRepo: Repository<User>,
) {}
async addUser(userDTO: UserDTO) {
const user = new UserDTO();
user.name = userDTO.name;
user.age = userDTO.age;
return await this.userRepo.save(user);
}
async getUserById(id) {
return await this.userRepo.findOne(id);
}
}
对应的user.controller.ts代码如下:
import { Controller, Post, Body } from '@nestjs/common';
import { UserService } from './user.service';
import { UserDTO } from './userDTO';
@Controller('user')
export class UserController {
constructor(
private readonly userService: UserService,
) {}
@Post()
addUser(@Body() userDTO: UserDTO) {
return this.userService.addUser(userDTO);
}
}
最后在user.module.ts写入如下代码:
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { User } from 'shared/entity/User';
import { UserService } from './user.service';
import { UserController } from './user.controller';
@Module({
imports: [TypeOrmModule.forFeature([User])],
providers: [UserService],
controllers: [UserController],
})
export class UserModule {}
然后我们用postman来新增一个用户
2018111308.png
加入platId于userDTO,新增User时指定所属平台
export class UserDTO {
...
@IsNumber()
platId: number;
}
在user.service.ts,修改新增与修改逻辑,
import { Injectable } from '@nestjs/common';
import { User } from 'shared/entity/User';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UserDTO } from './userDTO';
import { Platform } from 'shared/entity/Platform';
import { PlatformService } from 'feature/platform/platform.service';
@Injectable()
export class UserService {
constructor(
@InjectRepository(User)
private readonly userRepo: Repository<User>,
private platformService: PlatformService,
) {}
async addUser(userDTO: UserDTO) {
const user = new UserDTO();
user.name = userDTO.name;
user.age = userDTO.age;
// user.platId = data.platId; 不能只指定id,必须传入platform对象save的时候才会储存关联资料
user.plat = await this.platformService.getPlatformById(userDTO.platId);
return await this.userRepo.save(user);
}
async getUsers(): Promise<User[]>{
return await this.userRepo.find({relations: ['plat']}); // relations指定载入关联属性,是阵列,可能有多个导出属性
}
async getUserById(id) {
return await this.userRepo.findOne(id, {relations: ['plat']});
// relations指定载入关联属性,是阵列,可能有多个导览属性
// return await this.userRepo.findOneOrFail(id); // 以id搜寻,没找到会丢出例外
}
async updateUser(id, data: UserDTO){
const user = new User();
user.name = data.name;
user.age = data.age;
user.plat = await this.platformService.getPlatformById(data.platId);
return await this.userRepo.update(id, user); // 用data里的值更新到数据库
}
}
使用postman测试
2018111401.png
tuiguang.png推荐一下我的公众号: 【 geekjc 】,微信号: 【 c8706288 】一起学习交流编程知识,分享经验,各种有趣的事。
网友评论