Vona ORM分表全攻略

分表

针对高并发、数据量大的场景,通常会考虑采用分表机制进行优化。下面以 Model User/Order 为例,通过查询用户的订单列表,来演示分表的使用方法

分表规则

比如需要对订单表进行分表操作。可以根据实际业务需求设计分表规则,在这里,根据用户Id取模动态生成表名。比如,拆分为16张表,用户Id129,对应的表名如下:

typescript 复制代码
const tableName = `Order_${129 % 16}`;  // Order_1

准备Models

先准备两个 Models:User/Order

  1. Model Order
typescript 复制代码
@Model({
  entity: EntityOrder,
})
class ModelOrder{}
  1. Model User
typescript 复制代码
@Model({
  entity: EntityUser,
  relations: {
    orders: $relation.hasMany(() => ModelOrder, 'userId'),
  },
})
class ModelUser {}

查询数据

1. 直接查询订单列表

typescript 复制代码
class ServiceOrder {
  async selectOrdersDirectly() {
    const userId = 129;
    const orders = await this.scope.model.order.select({
      where: {
        userId,
      },
    });
  }
}  

到目前为止,使用默认表名查询userId=129的订单列表

2. 基于关系查询订单列表

typescript 复制代码
class ServiceOrder {
  async selectOrdersByRelation() {
    const userId = 129;
    const userAndOrders = await this.scope.model.user.get({
      id: userId,
    }, {
      include: {
        orders: true,
      },
    });
  }
}  

到目前为止,使用默认表名查询userId=129的用户信息,使用默认表名查询该用户的订单列表

使用分表:动态方式

可以在代码中动态使用分表:

diff 复制代码
class ServiceOrder {
  async selectOrdersDirectly() {
    const userId = 129;
+   const tableName = `Order_${userId % 16}`;
+   const modelOrder = this.scope.model.order.newInstance(undefined, tableName as any);
    const orders = await modelOrder.select({
      where: {
        userId,
      },
    });
  }
}  
  • newInstance: 传入要使用的表名,返回新的 Model 实例

到目前为止,使用分表查询userId=129的订单列表

使用分表:Relation动态选项

可以在 relation 选项中动态指定表名:

diff 复制代码
class ServiceOrder {
  async selectOrdersByRelation() {
    const userId = 129;
+   const tableName = `Order_${userId % 16}`;
    const userAndOrders = await this.scope.model.user.get({
      id: userId,
    }, {
      include: {
        orders: {
+         meta: {
+           table: tableName as any,
+         },
        },
      },
    });
  }
}  
  • meta.table: 指定 relation orders要使用的表名

到目前为止,使用默认表名查询userId=129的用户信息,使用分表查询该用户的订单列表

使用分表:Model配置

也可以直接在 Model 中配置分表规则,从而简化查询代码

  1. Model Order
diff 复制代码
@Model({
  entity: EntityOrder,
+ table(_ctx: VonaContext, where: EntityOrder | undefined, defaultTable: keyof ITableRecord) {
+   const userId = where?.userId;
+   if (!userId) return defaultTable;
+   return `Order_${Number(userId) % 16}`;
+ },
})
class ModelOrder{}
  • table: 指定函数,实现分表规则
  1. 查询数据

现在,又可以使用常规的方式查询用户的订单列表

typescript 复制代码
class ServiceOrder {
  async selectOrdersDirectly() {
    const userId = 129;
    const orders = await this.scope.model.order.select({
      where: {
        userId,
      },
    });
  }
}  
typescript 复制代码
class ServiceOrder {
  async selectOrdersByRelation() {
    const userId = 129;
    const userAndOrders = await this.scope.model.user.get({
      id: userId,
    }, {
      include: {
        orders: true,
      },
    });
  }
}  

使用分表:App Config配置

也可以在 App config 中配置 Model options:

src/backend/config/config/config.ts

typescript 复制代码
// onions
config.onions = {
  model: {
    'test-vona:order': {
      table(_ctx: VonaContext, where: EntityOrder | undefined, defaultTable: keyof ITableRecord) {
        const userId = where?.userId;
        if (!userId) return defaultTable;
        return `Order_${Number(userId) % 16}`;
      },
    },
  },
};

于是,也可以使用常规的方式查询用户的订单列表

使用分表:Relation静态选项

也可以在定义 Relation 时指定静态选项:

diff 复制代码
@Model({
  entity: EntityUser,
  relations: {
    orders: $relation.hasMany(() => ModelOrder, 'userId', {
+     meta: {
+       table(_ctx: VonaContext, where: EntityOrder | undefined, defaultTable: keyof ITableRecord) {
+         const userId = where?.userId;
+         if (!userId) return defaultTable;
+         return `Order_${Number(userId) % 16}`;
+       },
+     },
    }),
  },
})
class ModelUser {}

同样,也可以使用常规的方式查询用户的订单列表

Vona ORM已开源:github.com/vonajs/vona

相关推荐
codingWhat12 小时前
整理「祖传」代码,就是在开发脚手架?
前端·javascript·node.js
Wect12 小时前
LeetCode 210. 课程表 II 题解:Kahn算法+DFS 双解法精讲
前端·算法·typescript
ServBay12 小时前
Node.js、Bun 与 Deno,2026 年后端运行时选择指南
node.js·deno·bun
mCell15 小时前
从零构建一个 Mini Claude Code:面向初学者的 Agent 开发实战指南
typescript·agent·claude
敲敲敲敲暴你脑袋18 小时前
写个添加注释的vscode插件
javascript·typescript·visual studio code
码路飞19 小时前
Node.js 中间层我维护了两年,这周终于摊牌了——成本账单算完我人傻了
node.js
Wect20 小时前
LeetCode 207. 课程表:两种解法(BFS+DFS)详细解析
前端·算法·typescript
昨晚我输给了一辆AE862 天前
为什么现在不推荐使用 React.FC 了?
前端·react.js·typescript
None3212 天前
【NestJs】使用Winston+ELK分布式链路追踪日志采集
javascript·node.js
Wect2 天前
LeetCode 130. 被围绕的区域:两种解法详解(BFS/DFS)
前端·算法·typescript