Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use sequelize models in migration scripts

I would like to use a sequelize model in a migrations script. Is it possible, if yes, could you please provide an example? Thanks

I'm creating a table, account, after creating it with the migration script I would like to iterate over all the users (old users) which are not associated (~doesn't have an account yet) and create a new account for those old users. For this I wanted to use sequelize models to be able to write: User.findAll({ include: [Account], where: { Account: null } }) I understand that this is a little bit too exotic, and that I could write a sequel statement to create those accounts, but.. :D

When I try to require the sequelize model the migration always throws a [SyntaxError: Unexpected token =] error. Mind that I only require the model (Account) after the script creates the table (account). I don't have a syntax error in my model file, because otherwise it works, but when I try to use it in a migration script, it doesn't.

like image 584
Jim-Y Avatar asked Oct 30 '22 22:10

Jim-Y


2 Answers

Using models in migrations is not a good idea, as the model schema might be more advanced than the state of the database when the migration is being executed (for example, a field that was added in a later migration) which will cause the query to fail.

I suggest using queryInterface.sequelize.query in migrations.

like image 57
Dor 'Arie' Hanegby Avatar answered Nov 09 '22 06:11

Dor 'Arie' Hanegby


Just ran into this issue, it's just a matter of requiring the models and using them.

'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
  }
};
like image 25
dcohenb Avatar answered Nov 09 '22 04:11

dcohenb