跳到主要内容

模型定义

模型定义决定实体长什么样、如何关联、如何被查询。当前有三条建模入口:

  • @Entity():普通实体,来自 @aiao/rxdb
  • @TreeEntity():树结构实体,来自 @aiao/rxdb
  • @GraphEntity():图结构实体,来自 @aiao/rxdb-plugin-graph

最常见的是普通实体:

import { Entity, EntityBase, PropertyType } from '@aiao/rxdb';

@Entity({
name: 'Todo',
namespace: 'work',
tableName: 'todo',
displayName: '待办事项',
properties: [
{ name: 'title', type: PropertyType.string, required: true },
{ name: 'completed', type: PropertyType.boolean, default: false },
{ name: 'dueDate', type: PropertyType.date, nullable: true }
]
})
export class Todo extends EntityBase {}

一个实体实际由什么组成

@Entity() 接收的 EntityMetadataOptions 里,最常用的部分有:

  • name:实体名
  • namespace:命名空间,默认 public
  • tableName:数据库表名,不写时默认等于 name
  • properties:字段定义
  • relations:关系定义
  • indexes:索引定义
  • repository:仓库类型,普通实体默认 Repository
  • features:树、图等扩展特性

自动得到的能力

如果实体继承 EntityBase,框架会自动带上基础字段:

  • id
  • createdAt
  • updatedAt
  • createdBy
  • updatedBy

装饰器还会根据元数据补出这些运行时能力:

  • ONE_TO_ONE / MANY_TO_ONE 关系的外键字段,默认命名为 nameId
  • 关系访问属性,命名为 name$
  • 静态查询方法,如 findfindOnecount

先记住两个边界

  1. 实体静态查询方法返回的是 Observable,不是 Promise
  2. 图结构能力不在核心包里,使用 @GraphEntity 时还需要接入 @aiao/rxdb-plugin-graph

建模建议

  • 普通业务实体优先用 @Entity
  • 有父子层级且需要祖先/后代查询时,用 @TreeEntity + TreeAdjacencyListEntityBase
  • 需要边、路径、邻居查询时,用 @GraphEntity + GraphEntityBase
  • 单字段唯一约束直接写在属性上,多字段约束再用 indexes
  • 关系两端都要显式写清楚,不要依赖“推断另一端”

继续阅读