BDr*_*ght 5 node.js sequelize.js
我想知道是否可以使用 Sequelize 创建所需的模型,然后根据从请求收到的值使用模型。我尝试了不同的方法来完成此任务,但没有找到可行的解决方案。我承认它可能不存在。但如果是这样,有人知道如何实现这一目标吗?
const express = require('express');
const router = express.Router();
const Models = require('../models');
...
for (let modelName in tablesObj) {
if (modelName == primaryTable) {
Models.modelName.findAll()
.then(results => {
console.log(result);
});
}
}
Run Code Online (Sandbox Code Playgroud)
执行此操作的最佳方法是在/models目录中的加载程序中。Models它可以导出由模型名称作为键控的对象。
模型/index.js
const fs = require('fs');
const path = require('path');
const sequelize = // your db connection
// object to hold all the models to export
const models = {};
// Read all the files from this dir and load the models
fs.readdirSync(__dirname)
.forEach((file) => {
if (file !== path.basename(__filename) && file.endsWith('.js')) {
const model = sequelize.import(
path.join(__dirname, '/', file.replace(/\.js$/, ''))
);
models[model.name] = model;
}
});
/* anything else you want to do goes here */
// export the models
module.exports = models;
Run Code Online (Sandbox Code Playgroud)
现在您可以加载models并通过名称访问每一个。
其他.js
const models = require('../models');
async function runQuery() {
// access "modelName" model
const result = await models.modelName.findByPk(1);
// rest of your method
}
Run Code Online (Sandbox Code Playgroud)
我通常更进一步,将其加载models到创建 Express 应用程序的文件中,然后将模型设置为 的属性app并将其传递给路由器。
服务器.js
const Express = require('express');
const models = require('./models');
const app = new Express();
app.model = (model) => models[model];
Run Code Online (Sandbox Code Playgroud)
现在您可以像这样访问您的模型:
// assuming the model name is "Widget"
const widget = await app.models('Widget').findOne(...);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5775 次 |
| 最近记录: |