Search code examples
typescriptknex.jsadonis.js

Add new column to existing database table


I have created a model and migration using node ace make:migration user and node ace make:model user, now I want to add another column to the user model.

How do I add another new column after already creating a model and migration?


Solution

  • Here the KnexJS documentation about migrations : https://knexjs.org/#Schema-Building

    AdonisJS documentation : https://docs.adonisjs.com/guides/database/migrations#alter-example

    How to create new column

    Create new migration file

    node ace make:migration add_new_column --table=users
    

    Update code in migration file

    import BaseSchema from '@ioc:Adonis/Lucid/Schema'
    
    export default class Users extends BaseSchema {
      protected tableName = 'users'
    
      public async up () {
        this.schema.table(this.tableName, (table) => {
          // Create new column with table.<type>(<name>)
          table.text('my_new_column')
        })
      }
    
      public async down () {
        this.schema.table(this.tableName, (table) => {
          table.dropColumn('my_new_column')
        })
      }
    }