Sequelize中获取列列表是否有更简便方法?解决attributes无智能提示痛点
解决Sequelize中attributes数组无智能提示的简便方法
使用Sequelize时,where条件里的列名能通过智能提示快速输入,但attributes作为字符串数组时没有智能提示,之前手动临时创建where再转换的方式太繁琐,这里分享几个更高效的方法:
1. TypeScript类型推导(推荐)
如果项目用TypeScript,直接利用模型的类型定义约束attributes数组,就能触发智能提示:
// 导出模型的列名类型 type MyTableColumnNames = keyof typeof MyTableModel['rawAttributes']; // 定义attributes为该类型的数组,自动触发智能提示 const res = await MyTableModel.findAll({ attributes: ['att1', 'att2'] as MyTableColumnNames[] });
更简洁的写法:
const res = await MyTableModel.findAll({ attributes: <MyTableColumnNames[]>['att1', 'att2'] });
2. 直接用模型的rawAttributes属性
不管是JS还是TS项目,都可以通过MyTableModel.rawAttributes获取列名智能提示:
- 输入
MyTableModel.rawAttributes.,编辑器会列出所有列名,直接选择需要的列名 - 利用编辑器多光标功能(比如VS Code按住Alt点击),选中多个列名后,批量添加引号和逗号,快速转换成数组形式
示例操作:
- 输入
MyTableModel.rawAttributes.att1,选中att1 - 按住Alt点击下一行,输入
MyTableModel.rawAttributes.att2,选中att2 - 按Ctrl+Shift+引号键,给所有选中列名加引号
- 复制带引号的列名,粘贴到attributes数组中调整逗号即可
3. JSDoc增强JavaScript智能提示
纯JavaScript项目中,用JSDoc给attributes数组指定类型,VS Code也能识别并给出智能提示:
/** @type {Array<keyof typeof MyTableModel['rawAttributes']>} */ const attributes = ['att1', 'att2']; const res = await MyTableModel.findAll({ attributes });
这些方法都比手动临时创建where再转换高效得多,不用来回切换文档或重复繁琐操作。
内容的提问来源于stack exchange,提问作者enoeht
相关产品推荐
相关产品推荐

