乐闻世界logo
搜索文章和话题

How to add column in Sequelize existing model?

1个答案

1

Adding a column in Sequelize typically involves two steps: first, updating the model definition, and then migrating the database to reflect these changes. Here are the detailed steps and examples:

Step 1: Update the Model Definition

Suppose we have a model named User, and we need to add a column named age to it. First, add this new column to the model definition:

javascript
const { Model, DataTypes } = require('sequelize'); const sequelize = require('../path/to/your/sequelize_instance'); class User extends Model {} User.init({ // Existing columns username: DataTypes.STRING, email: DataTypes.STRING, // New column age: DataTypes.INTEGER }, { sequelize, modelName: 'User' }); module.exports = User;

In this example, we add a column named age with an integer data type.

Step 2: Database Migration

After updating the model, we need to add this column to the database. This can be achieved by manually modifying the database, using Sequelize's migration tool, or other database migration tools.

Using Sequelize Migration Tool

  1. Generate the migration file: First, generate a migration file using Sequelize's command-line tool:

    bash
    npx sequelize-cli migration:generate --name add-age-to-users

    This creates a new migration file in the project's migrations directory.

  2. Write the migration logic: In the generated migration file, write the code to add the new column:

    javascript
    'use strict'; module.exports = { up: async (queryInterface, Sequelize) => { await queryInterface.addColumn('Users', 'age', { type: Sequelize.INTEGER, allowNull: true }); }, down: async (queryInterface, Sequelize) => { await queryInterface.removeColumn('Users', 'age'); } };

    In this migration file, the up method adds the column, while the down method removes it for rollback purposes.

  3. Execute the migration: Run the following command to apply the migration:

    bash
    npx sequelize-cli db:migrate

By following these steps, we add the new column both at the model level and in the database, ensuring consistency between the code and the database.

2024年8月8日 22:11 回复

你的答案