How to alter columns without losing data? #3456
-
I followed the guide provided in the documentation. My use case is to make a column foreign key. I used alterTable method and added my changes to the column. I ran the migrations, it didn't worked. But when I added alter() method to the columns, it worked! I thought alterTable will alter columns too. Can you please guide me what happened here? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
My understanding is So, for example, if I need to add a new column "summary" and alter an existing column called "body" from type varchar to text, my migration would look like this: this.schema.alterTable(this.tableName, table => {
table.string('summary') // 👈 adds new column
table.text('body').alter() // 👈 changes type from varchar to text
}) Here's the documentation on |
Beta Was this translation helpful? Give feedback.
My understanding is
alterTable
, by default, can handle adding and removing columns (since removing has its own method(s)). Thealter
method comes into play when you need to actually alter an existing column.So, for example, if I need to add a new column "summary" and alter an existing column called "body" from type varchar to text, my migration would look like this:
Here's the documentation on
alter()
if you're interested:https://knexjs.org/#Schema-alter