我可以在迁移脚本中使用序列化模型吗?

Can I use sequelize models in migration scripts

本文关键字:序列化 模型 迁移 脚本 我可以      更新时间:2023-09-26

我想在迁移脚本中使用序列化模型。如果可以,能否提供一个例子?由于

我正在创建一个表,帐户,在使用迁移脚本创建它之后,我想遍历所有未关联的用户(老用户)(~还没有帐户),并为这些旧用户创建一个新帐户。为此,我想使用sequelize模型来编写:User.findAll({ include: [Account], where: { Account: null } })我知道这有点太奇怪了,我可以写一个sequel语句来创建这些帐户,但是……: D

当我尝试要求序列化模型时,迁移总是抛出[SyntaxError: Unexpected token =]错误。请注意,在脚本创建表(帐户)之后,我只需要模型(帐户)。我在模型文件中没有语法错误,因为否则它会工作,但是当我试图在迁移脚本中使用它时,它不会。

在迁移中使用模型并不是一个好主意,因为模型模式可能比执行迁移时数据库的状态更高级(例如,在以后的迁移中添加的字段),这将导致查询失败。

我建议在迁移中使用queryInterface.sequelize.query

刚刚遇到这个问题,这只是一个需要模型和使用它们的问题。

'use strict';
const { User, Account } = require('../models'); // Assuming migrations is next to models
module.exports = {
  up: async (queryInterface, Sequelize) => {
    // Make the database migrations
    await queryInterface.createTable('Accounts', .......)
    await queryInterface.addColumn('Users', 'AccountId', {
      type: Sequelize.INTEGER,
      references: { model: 'Accounts', key: 'id' }
      // ... more stuff here
    })
    // Fill up data
    const usersWithoutAccounts = await User.findAll({ where: {AccountId: null}})
    await Promise.all(usersWithoutAccounts.map(async user => {
      const account = await Account.create({ props })
      await user.update({ AccountId: account.id })
    }))
  },
  down: async (queryInterface, Sequelize) => {
    // ... undo changes
  }
};