【问题标题】:How to update a constraint in a migration如何在迁移中更新约束
【发布时间】:2020-03-04 20:45:35
【问题描述】:

我需要将 onDelete 和 onUpdate 级联添加到迁移文件中的约束。

所以我做了一个 alter table,选择外键并在每个命令末尾使用 alter 方法链接。

class UpdateRecipientSchema extends Schema {
  up () {
    this.alter('deliveries', (table) => {
      table.integer('recipient_id')
        .unsigned()
        .references('id')
        .inTable('recipients')
        .onDelete('CASCADE')
        .onUpdate('CASCADE')
        .notNullable()
        .alter()
      table.integer('courier_id')
        .unsigned()
        .references('id')
        .inTable('couriers')
        .notNullable()
        .onDelete('CASCADE')
        .onUpdate('CASCADE')
        .alter()
    })
  }

  down () {
    this.alter('deliveries', (table) => {
      table.integer('recipient_id')
        .unsigned()
        .references('id')
        .inTable('recipients')
        .notNullable()
        .alter()

      table.integer('courier_id')
        .unsigned()
        .references('id')
        .inTable('couriers')
        .notNullable()
        .alter()
    })
  }
}

但我收到一条错误消息,指出这种关系的约束已经存在。错误:constraint "deliveries_courier_id_foreign" for relation "deliveries" already exists

如何在迁移中更新表的约束?

【问题讨论】:

    标签: javascript node.js postgresql knex.js adonis.js


    【解决方案1】:

    首先我必须删除外键列,然后重新创建它。

    我们可以在迁移中使用任意代码来做到这一点

    await Database.raw('DROP FOREIGN KEY deliveries_courier_id_foreign')
    // And now recreate it
    await Database.raw('...')
    

    我们也可以使用this.schedule函数来执行多个事情https://adonisjs.com/docs/4.1/migrations#_executing_arbitrary_code

    感谢在 Adonis 论坛上帮助我的人 https://forum.adonisjs.com/t/how-to-update-a-constraint-in-a-migration/5835

    【讨论】:

      猜你喜欢
      • 2023-03-22
      • 1970-01-01
      • 2016-12-24
      • 2011-06-07
      • 2020-03-21
      • 1970-01-01
      • 1970-01-01
      • 2011-08-06
      • 1970-01-01
      相关资源
      最近更新 更多