nestjs系列 - entity的搭建
type
status
date
slug
summary
tags
category
icon
password
 
 
@Entity()
定义类为实体,定义实体对应表名称
 
@Index()
@PrimaryGeneratedColumn({ type: 'bigint' })
 
 
细节1 - 不设置column类型,默认是int8
 
细节2 - ts的可空类型无法直接对应数据库
 
细节3 - 类默认值无法直接对应数据库
 
 
1 配置一个字段是枚举类型
 
 
2 多对一关联
 
AdBanner.ExhibitionId 关联Exhibition表
notion image
 
 
 
级联操作
一对多和多对一的理解: 只是同一个关系的两个不同实体角度而已
notion image
notion image
 
Inner, Outer, Left, Right 理解
 
非空设计设计需要考虑的问题
notion image
notion image
 
 
从现有数据库生成entity
使用typeorm-model-generator库快速生成
 
 
实现写入更新时间、软删除逻辑
 
实现lastModifyDatecreateDate字段的自动更新有两种方法
 
  • lastModifyDatedeleteDatecreateDate字段加上@CreateDateColumn、@UpdateDateColumn@DeleteDateColumn
 
  • 使用监听事件实现lastModifyDatecreateDate 自动化更新
 
这里因为每个表都有该字段,所以为了高效,让所有实体都有继承自定义的EntityBase 类,在EntityBase 里面完成上述操作
 
 
参考:
Feature: Soft Delete
Updated Aug 8, 2023
notion image
notion image

© ittat 2016-2025