我有以下代码:
const service = await Service.findByPk(req.params.service_id, {
include: [
{
model: User,
attributes: {
exclude: ['password'],
},
},
],
});
有什么方法可以让我用模型的名称替换模型 User ,这样我就不必导入 User 模型了吗?
最佳答案
选项 1. 您可以使用 sequelize.models 属性。
Models are stored here under the name given to
sequelize.define
但是您仍然需要导入
Sequelize
类的实例。import { Service } from './models';
import { sequelize } from '../../db';
async function controller(req, res) {
const service = await Service.findByPk(req.params.service_id, {
include: [
{
model: sequelize.models['User'],
attributes: {
exclude: ['password'],
},
},
],
});
}
db.js
:import { Sequelize } from 'sequelize';
const sequelize = new Sequelize({
dialect: 'postgres',
//...
})
export { sequelize }
选项 2. 您可以使用 Model.sequelize 。A reference to the sequelize instance
这样就不需要导入
Sequelize
类的实例了。您可以从 Model.sequelize
属性获取实例。import { Service } from './models';
async function controller(req, res) {
const service = await Service.findByPk(req.params.service_id, {
include: [
{
model: Service.sequelize.models['User'],
attributes: {
exclude: ['password'],
},
},
],
});
}
关于node.js - 如何在 Sequelize 中使用模型名称而不是模型本身进行急切加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65398094/