[使用Sequelize提取数据时,如何在MySQL QL查询中将MySQL日期时间字段输出为字符串?
这是我的表的(简化)结构:
CREATE TABLE `things` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`start_date` datetime DEFAULT NULL,
`creation_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
这是我的(简化的)Sequelize模型:
module.exports = function(sequelize, DataTypes) {
return sequelize.define('things', {
id: {
type: DataTypes.INTEGER(10).UNSIGNED,
allowNull: false,
primaryKey: true,
autoIncrement: true
},
start_date: {
type: DataTypes.DATE,
allowNull: true
},
creation_date: {
type: DataTypes.DATE,
allowNull: false,
defaultValue: sequelize.literal('CURRENT_TIMESTAMP')
},
}, {
tableName: 'things',
timestamps: false
});
};
这是我的GraphQL模式定义:
import { gql } from 'apollo-server-express'
import * as db from '../database'
export const typeDefs = gql`
extend type Query {
things: [Thing]
}
type Thing {
id: ID!
creationDate: String
startDate: String
}
`
export const resolvers = {
Query: {
things: async () => db.things.findAll(),
},
}
[当我运行things
查询时,对于null
和creationDate
字段总是得到startDate
。我想获取的是日期和时间,为ISO 8601格式的字符串。
之所以收到null是因为Sequelize返回的对象的属性名称与您的字段名称不匹配(creation_date
与creationDate
)。有关详细说明,请参见this post。
无论如何,您仍然需要提供一个自定义解析程序来格式化日期。没有它,您将最终获得纪元日期。您将需要执行以下操作:
const resolvers = {
Thing: {
creationDate: (thing) => {
// thing is an instance of your Sequelize model
// thing.creation_date is an instance of Date
return thing.creation_date.toISOString()
},
},
}