【问题标题】:How to alter postgres sql constraint with Knex?如何使用 Knex 更改 postgres sql 约束?
【发布时间】:2021-10-13 22:21:53
【问题描述】:

表是通过以下方式创建的:

exports.up = function (knex) {
  return knex.schema.createTable('organisations_users', (table) => {
    table.uuid('organisation_id').notNullable().references('id').inTable('organisations').onDelete('SET NULL').index();
};

exports.down = function (knex) {
  return knex.schema.dropTableIfExists('organisations_users');
};

在另一个迁移文件中,我想将onDelete 命令更改为“CASCADE”。

我尝试过(除其他外):

exports.up = function (knex) {
  return knex.schema.alterTable('organisations_users', (table) => {
      table.uuid('organisation_id').alter().notNullable().references('id').inTable('organisations').onDelete('CASCADE').index();
    });
};

但是 knex 声明约束已经存在(这是真的,这就是我想要改变它的原因)

这个命令是什么?我也可以使用 knex.raw 字符串。

谢谢

【问题讨论】:

  • 您可以从模式中检查,删除表时在数据库中留下了哪个约束。如果您查看运行迁移时执行了哪些查询,也可能会有所帮助。简单的方法是在运行迁移之前设置export DEBUG=knex:*

标签: postgresql knex.js


【解决方案1】:

通过以下方式解决它:

exports.up = function (knex) {
  return knex.schema.alterTable('organisations_users', async (table) => {

      // First drop delete references
      await knex.raw('ALTER TABLE organisations_users DROP CONSTRAINT IF EXISTS organisations_users_organisation_id_foreign')
      

      // Add the correct delete command (was SET NULL, now CASCADE)
      table.uuid('organisation_id').alter().notNullable().references('id').inTable('organisations').onDelete('CASCADE');
    });
};

exports.down = function (knex) {
  return knex.schema.dropTableIfExists('organisations_users');
};

【讨论】:

    猜你喜欢
    • 2020-04-16
    • 1970-01-01
    • 2012-02-04
    • 1970-01-01
    • 2022-10-04
    • 2012-10-26
    • 1970-01-01
    • 1970-01-01
    • 2021-05-23
    相关资源
    最近更新 更多