簡體   English   中英

在 Node.js 和 Knex 中向現有表添加一列

[英]Adding a column to an existing table in Node.js & Knex

我正在使用 Node.js 和 Knex 為我的路由器構建服務。 但是,我不知道如何向現有表添加列,我們將不勝感激。 另外,我使用的是 PostgreSQL,但我認為這對問題並不重要。

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

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

我猜向表中添加一列會與此類似嗎? 我只是無法弄清楚/找到解決方案。

上面的答案是正確的,除了...

請務必寫上“knex.schema。ALTERTABLE”,而不是“knex.schema.table”。

下面是正確的:

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

您應該使用 Knex.js 提供的架構構建功能

以下是其官方文檔中的示例:

//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);

對於遷移:

這是從這篇 文章中提取的

  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

1.運行這個:

knex 遷移:制作 add_new_column_to_table

2.將創建一個新文件'20220524120511_dd_new_column_to_table.js'

使用此代碼:


exports.up = async function (knex) {
    await knex.schema.table("table_name", (table) => {
    table.string("column_name", 128);
  });
};

exports.down = async function (knex) {
    await knex.schema.table("table_name", (table) => {
    table.dropColumn("column_name");
  });
};

  1. 運行這個:

knex遷移:最新

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM