如何将列类型从 CHAR 更改为 DATE
How to change column type from CHAR to DATE
我之前将日期字段保存为CHAR,现在我想使用Sequelize迁移将日期字段从CHAR更新为DATE。日期列的格式为 2021-03-08T20:09:49Z
(UTC)。
module.exports = {
up: async (queryInterface, Sequelize) => {
try {
await queryInterface.changeColumn("my_table", "my_date_col", {
type: Sequelize.DATE,
});
return Promise.resolve();
} catch (e) {
return Promise.reject(e);
}
},
但是我得到了这个错误:ERROR: column "my_date_col" cannot be cast automatically to type.
我想问一下如何在 Sequelize for Postgres DB 中将 CHAR 转换为 DATE?谢谢。
我自己想出来的。需要先将CHAR转为TIMESTAMP,再设置为DATE类型。
这种方法的缺点是它将现有数据从 UTC 转换为我当地的时区,但我很喜欢它。
module.exports = {
up: async (queryInterface, Sequelize) => {
try {
await queryInterface.changeColumn("my_table", "my_date_col", {
type: 'TIMESTAMP USING CAST("my_date_col" as TIMESTAMP)',
});
await queryInterface.changeColumn("my_table", "my_date_col", {
type: Sequelize.DATE,
});
return Promise.resolve();
} catch (e) {
return Promise.reject(e);
}
},
down: async (queryInterface, Sequelize) => {
try {
await queryInterface.changeColumn("my_table", "my_date_col", {
type: Sequelize.STRING,
});
return Promise.resolve();
} catch (e) {
return Promise.reject(e);
}
},
};
我之前将日期字段保存为CHAR,现在我想使用Sequelize迁移将日期字段从CHAR更新为DATE。日期列的格式为 2021-03-08T20:09:49Z
(UTC)。
module.exports = {
up: async (queryInterface, Sequelize) => {
try {
await queryInterface.changeColumn("my_table", "my_date_col", {
type: Sequelize.DATE,
});
return Promise.resolve();
} catch (e) {
return Promise.reject(e);
}
},
但是我得到了这个错误:ERROR: column "my_date_col" cannot be cast automatically to type.
我想问一下如何在 Sequelize for Postgres DB 中将 CHAR 转换为 DATE?谢谢。
我自己想出来的。需要先将CHAR转为TIMESTAMP,再设置为DATE类型。
这种方法的缺点是它将现有数据从 UTC 转换为我当地的时区,但我很喜欢它。
module.exports = {
up: async (queryInterface, Sequelize) => {
try {
await queryInterface.changeColumn("my_table", "my_date_col", {
type: 'TIMESTAMP USING CAST("my_date_col" as TIMESTAMP)',
});
await queryInterface.changeColumn("my_table", "my_date_col", {
type: Sequelize.DATE,
});
return Promise.resolve();
} catch (e) {
return Promise.reject(e);
}
},
down: async (queryInterface, Sequelize) => {
try {
await queryInterface.changeColumn("my_table", "my_date_col", {
type: Sequelize.STRING,
});
return Promise.resolve();
} catch (e) {
return Promise.reject(e);
}
},
};