How to do knex.js migrations?

前端 未结 6 1451
天命终不由人
天命终不由人 2021-02-01 19:39

I\'m still not sure how to do my migrations with knex. Here is what I have so far. It works on up, but down gives me FK constraint error even though fo

6条回答
  •  情话喂你
    2021-02-01 20:05

    Subjectively as the most clean way to do it I would suggest including in your migration file something like:

    exports.up = function (knex) {
      return Promise.all([
        knex.schema.createTable('users', function (table) {
          table.increments('id')
          table.string('username').notNullable()
          table.string('password').notNullable()
          table.string('service').notNullable()
          table.text('cookies')
          table.enu('status', ['active', 'disabled', 'need_login', 'failed']).defaultTo('need_login').notNullable()
          table.datetime('last_checked')
          table.timestamps()
        }),
        knex.schema.createTable('products', function (table) {
          table.increments()
          table.integer('user_id').unsigned().notNullable()
          table.string('title')
          table.decimal('price', 8, 2)
          table.text('notes')
          table.enu('status', ['to_publish', 'published', 'hidden', 'not_found']).notNullable()
          table.timestamps()
          table.foreign('user_id').references('id').inTable('users')
        }),
        knex.schema.createTable('messages', function (table) {
          table.increments()
          table.integer('user_id').unsigned().notNullable()
          table.integer('product_id').unsigned().notNullable()
          table.boolean('incoming')
          table.boolean('unread')
          table.text('text')
          table.timestamps()
          table.foreign('user_id').references('id').inTable('users')
          table.foreign('product_id').references('id').inTable('products')
        })
      ])
    }
    
    exports.down = function (knex) {
      return Promise.all([
        knex.schema.dropTable('messages'),
        knex.schema.dropTable('products'),
        knex.schema.dropTable('users')
      ])
    }
    

提交回复
热议问题