更新 knex 迁移中的枚举列类型

编程入门 行业动态 更新时间:2024-10-27 06:25:01
本文介绍了更新 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 迁移中的枚举列类型

本文发布于:2023-10-17 22:10:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1502221.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   knex

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!