![](/img/trans.png)
[英]Why Sequelize migration create table but models can not connect to a database
[英]Can I use sequelize models in migration scripts
我想在遷移腳本中使用續集模型。 有沒有可能,如果有,能否舉個例子? 謝謝
我正在創建一個表,帳戶,在使用遷移腳本創建它之后,我想遍歷所有未關聯的用戶(舊用戶)(~還沒有帳戶)並為這些用戶創建一個新帳戶老用戶。 為此,我想使用續集模型來編寫: User.findAll({ include: [Account], where: { Account: null } })
我知道這有點太奇特了,我可以寫創建這些帳戶的續集聲明,但是.. :D
當我嘗試要求 sequelize 模型時,遷移總是拋出[SyntaxError: Unexpected token =]
錯誤。 請注意,在腳本創建表(帳戶)后,我只需要模型(帳戶)。 我的模型文件中沒有語法錯誤,因為否則它可以工作,但是當我嘗試在遷移腳本中使用它時,它沒有。
剛剛遇到這個問題,這只是需要模型並使用它們的問題。
'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
}
};
在遷移中使用模型不是一個好主意,因為模型模式可能比執行遷移時數據庫的狀態(例如,在以后遷移中添加的字段)更高級,這將導致查詢失敗。
我建議在遷移中使用queryInterface.sequelize.query
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.