如何在 sequelize 中预先加载模型名称而不是模型本身

How to eager load with model name instead of model itself in sequelize

我有以下代码:

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 class.

的实例
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

这样就不需要导入Sequelizeclass的实例了。您可以从 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'],
        },
      },
    ],
  });
}