实体属性
实体(Entity)是数据模型的基本单位,代表数据库中的一张表。属性用于描述实体的字段及其约束。
在 Aiao RxDB 中,通过 @Entity 装饰器在类上定义属性与关系;所有实体应继承 EntityBase,该基类会自动提供通用字段(id/createdAt/updatedAt/...)。
import { Entity, EntityBase, PropertyType } from '@aiao/rxdb';
@Entity({
name: 'User',
displayName: '用户',
properties: [
{ name: 'name', type: PropertyType.string, displayName: '姓名' },
{ name: 'email', type: PropertyType.string, unique: true, displayName: '邮箱' }
]
})
export class User extends EntityBase {}
内置基础字段
所有继承 EntityBase 的实体自动拥有以下只读字段(无需在 properties 中重复声明):
- id:
uuid主键,默认自动生成 - createdAt/updatedAt:
date,默认自动填充当前时间 - removedAt/createdBy/updatedBy/removedBy: 支持审计和软删除(可空)
属性类型(type)
支持的类型如下:
| 类型 | 说明 | 示例 |
|---|---|---|
uuid | UUID | 主键或业务 ID |
string | 字符串 | 姓名、邮箱、地址等 |
number | 数字 | 价格、金额 |
integer | 整数 | 年龄、数量等 |
boolean | 布尔 | 是否激活、是否默认等 |
date | 日期 | 创建时间、更新时间等 |
stringArray | 字符串数组 | ["a","b","c"] |
numberArray | 数字数组 | [1,2,3] |
keyValue | 值对象 | { "a":1, "b":2 }(扁平KV) |
json | JSON 对象 | { "a":1, "b":["1","2"] } |
属性选项(按类型)
核心通用选项来源于接口 IEntityObject 与 ISortable:
- name: 字段名(小写开头英文/下划线)
- displayName?: 显示名
- unique?: 是否唯一(为 true 时会生成唯一索引)
- readonly?: 是否只读(更新时忽略)
- nullable?: 是否可空
- sortable?: 是否可排序(查询层支持排序)
部分类型支持额外选项:
uuid/integer:primary?: boolean(是否主键)- 所有类型:
default?: T | () => T(支持函数默认值) keyValue:properties: KeyValuePropertyMetadataOptions[](描述值对象内部键值类型)
示例:
@Entity({
name: 'Product',
properties: [
{
name: 'title',
type: PropertyType.string,
displayName: '商品标题',
unique: true,
default: '未命名商品',
sortable: true
},
{
name: 'tags',
type: PropertyType.stringArray,
default: () => []
},
{
name: 'attrs',
type: PropertyType.keyValue,
properties: [
{ name: 'brand', type: PropertyType.string },
{ name: 'weight', type: PropertyType.number }
]
}
]
})
export class Product extends EntityBase {}
提示:单字段唯一请直接在属性上使用 unique: true;联合唯一或联合索引请参考“实体索引”。