我需要将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

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

最佳答案

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

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

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中帮助我的那个人

关于javascript - 如何在迁移中更新约束,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60534423/

10-11 04:56
查看更多