How to do knex.js migrations?

前端 未结 6 1524
天命终不由人
天命终不由人 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

    I solved this problem by using a transaction

    transation.js

    module.exports = function transaction(fn) {
        return function _transaction(knex, Promise) {
            return knex.transaction(function(trx) {
                return trx
                    .raw('SET foreign_key_checks = 0;')
                    .then(function() {
                        return fn(trx, Promise);
                    })
                    .finally(function() {
                        return trx.raw('SET foreign_key_checks = 1;');
                    });
            });
        };
    }
    

    Migration file

    var transaction = require('../transaction');
    
    function up(trx, Promise) {
        return trx.schema
           .createTable('contract', function(table) {
               table.boolean('active').notNullable();                                              
               table.integer('defaultPriority').unsigned().references('priority.id');                             
               table.integer('defaultIssueStatus').unsigned().references('issueStatus.id');
               table.integer('owner').notNullable().unsigned().references('user.id'); 
           })
    
           .createTable('user', function (table) {
               table.increments('id').primary();
               table.datetime('createdAt');
               table.datetime('updatedAt');
    
               table.string('phoneNumber').notNullable().unique();
               table.string('password').notNullable();            
               table.string('name').notNullable().unique();       
               table.string('email');                             
               table.string('status');                            
               table.string('roles').defaultTo('user');           
               table.integer('contract').unsigned().references('contract.id');
           });
    }
    
    function down(trx, Promise) {
        return trx.schema
            .dropTable('contract')
            .dropTable('user');
    }
    
    exports.up = transaction(up);
    exports.down = transaction(down);
    

提交回复
热议问题