无法在迁移中使用查询功能

Can't use query function in migration

我正在尝试使用 Sequelize 在 JavaScript 的迁移文件中提出一个简单的 SELECT 请求。

使用此代码:

const Sequelize = require("sequelize");
const { query, QueryTypes } = use_env_variable
  ? new Sequelize(process.env[use_env_variable], config)
  : new Sequelize(database, username, password, config);

module.exports = {
  up: async ({ addColumn, removeColumn }, { INTEGER }) => (
    const results = await query("SELECT * FROM table;", { type: QueryTypes.SELECT });
  ),
  down: async () => {}
});

我遇到了错误:

ERROR: Cannot read property 'options' of undefined

同时,如果我不专门从 sequelize 中仅导入 queryQueryTypes 并使用约定的 sequelize.querysequelize.QueryTypes.SELECT 它将起作用:

const Sequelize = require("sequelize");
const sequelize = use_env_variable
  ? new Sequelize(process.env[use_env_variable], config)
  : new Sequelize(database, username, password, config);

module.exports = {
  up: async ({ addColumn, removeColumn }, { INTEGER }) => (
    const results = await sequelize.query("SELECT * FROM table;", { type: sequelize.QueryTypes.SELECT });
  ),
  down: async () => {}
});

上面的代码在我需要的方式下运行良好,但为什么呢?如果我混合使用这两种代码以使 sequelize.queryquery 像那样导入:

const Sequelize = require("sequelize");
const sequelize = use_env_variable
  ? new Sequelize(process.env[use_env_variable], config)
  : new Sequelize(database, username, password, config);
const { query, QueryTypes } = use_env_variable
  ? new Sequelize(process.env[use_env_variable], config)
  : new Sequelize(database, username, password, config);

我认为 console.log(query === sequelize.query); 会 return true 但使用 query 而不是 sequelize.query 会引发 ERROR: Cannot read property 'options' of undefined 错误.. .

我哪里做错了?

Slack 续集的某个人回答了我:

It's normal. query is a method that needs to know the instance it's being called on. If you extract it from the sequelize instance, its this will be undefined instead of the sequelize instance you can do this though:

const sequelize = new Sequelize(process.env[config.use_env_variable], config);
const { QueryTypes } = sequelize;
const query = sequelize.query.bind(sequelize);