【问题标题】:Adding a column to an existing table in Node.js & Knex在 Node.js 和 Knex 中向现有表添加列
【发布时间】:2020-06-26 14:59:46
【问题描述】:

我正在使用 Node.js 和 Knex 为我的路由器构建服务。但是,我不知道如何将列添加到现有表中,任何帮助将不胜感激。 另外,我使用的是 PostgreSQL,但我认为这对这个问题并不重要。

所以,这就是我向表中添加行的方法:

insertData(knex, table, row) {
  return knex
    .insert(row)
    .into(table)
    .returning('*')
    .then(rows => {
      return rows[0];
    });
}

我猜在表格中添加一列会与此类似?我只是想不出/找到解决方案。

【问题讨论】:

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


    【解决方案1】:

    以上答案都是正确的,除了...

    确保写成“knex.schema.alterTable”而不是“knex.schema.table”。

    以下是正确的:

     return knex.schema.alterTable('<table name>', table => {
        table.dropColumn('<new column name>');
      })
    

    【讨论】:

      【解决方案2】:

      对于迁移:

      取自article

      1. 首先进行迁移:

      knex migrate:make add_new_column_to_table

      1. 然后在迁移中将文件更新为:
      exports.up = function(knex) {
        return knex.schema.table('<table name>', table => {
          table.string('<new column name>', 128);
        })
      };
      
      exports.down = function(knex) {
        return knex.schema.table('<table name>', table => {
          table.dropColumn('<new column name>');
        })
      };
      
      1. 然后运行迁移:

      knex migrate:latest

      【讨论】:

        【解决方案3】:

        你应该使用 Knex.js 提供的 Schema Building 功能

        以下是来自its official documentation的示例:

        //Chooses a database table, and then modifies the table
        
        knex.schema.table('users', function (table) {
          table.string('first_name');
          table.string('last_name');
        })
        
        //Outputs:
        //alter table `users` add `first_name` varchar(255), add `last_name` varchar(255);
        

        【讨论】:

          猜你喜欢
          • 2022-10-04
          • 1970-01-01
          • 1970-01-01
          • 2015-12-25
          • 2014-06-21
          • 2011-06-17
          • 2023-03-10
          • 1970-01-01
          • 2013-05-23
          相关资源
          最近更新 更多