Update enum column types in knex migration(更新 knex 迁移中的枚举列类型)
本文介绍了更新 knex 迁移中的枚举列类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找编写迁移字符串以将新字符串添加到枚举列类型.我正在尝试将 gamma
添加到 service
列.
I'm looking to write a migration string to add a new string to the enum column type. I'm trying to add gamma
to the service
column.
我尝试使用下面的代码.发生冲突是因为表和列已经存在.
I tried with this code below. This collides because the table and the column already exists.
const table = 'user_associations'
export function up (knex, Promise) {
return knex.schema.table(table, function (table) {
table.enu('service', ['alpha', 'beta', 'gamma']).notNullable()
})
}
export function down (knex, Promise) {
return knex.schema.table(table, function (table) {
table.enu('service', ['alpha', 'beta']).notNullable()
})
}
推荐答案
const tableName = 'user_associations'
export function up (knex, Promise) {
let existRows;
return knex.select()
.from(tableName)
.then((rows) => {
existRows = rows
return knex.schema.table(tableName, (table) => table.dropColumn('service'))
})
.then(() => knex.schema.table(tableName, (table) => table.enu('service', ['alpha', 'beta', 'gamma']).notNullable().default('alpha')))
.then(() => {
return Promise.all(existRows.map((row) => {
return knex(tableName)
.update({ service: row.service })
.where('id', row.id)
}))
})
}
export default down(kenx, Promise) {
let existRows;
return kenx.select()
.from(tableName)
.then((rows) => {
existRows = rows
return knex.schema.table(tableName, (table) => table.dropColumn('service'))
})
.then(() => knex.schema.table(tableName, (table) => table.enu('service', ['alpha', 'beta']).notNullable().default('alpha')))
.then(() => {
return Promise.all(existRows.map((row) => {
return knex(tableName)
.update({ service: row.service === 'gamma' ? 'alpha' : row.service })
.where('id', row.id)
}))
})
}
- notNull 列需要默认值吗?
- 最好不要使用枚举,因为它不是响应式的...我将在代码中使用微小的整数字段和常量来控制可选字段
这篇关于更新 knex 迁移中的枚举列类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:更新 knex 迁移中的枚举列类型


基础教程推荐
猜你喜欢
- 动态更新多个选择框 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 在for循环中使用setTimeout 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01