【问题标题】:Formatting return Type of the column in Sequelize格式化返回 Sequelize 中列的类型
【发布时间】:2018-09-25 20:31:42
【问题描述】:

我使用 Sequelize 来说明我的专栏之一的类型如下:

userTime: DataTypes.TIME 

这会将 MS SQL 中的列声明为time(7) 格式。
我将数据作为字符串添加到相应的列。例如:“12:00”
但是,当我从数据库中检索数据时,它以以下格式显示:

userTime: "1970-01-01T12:00:00.000Z" 

如何使用 Sequelize 将输出更改为以下格式:
用户时间:“12:00”

是否有可能在 Sequelize 中使用返回类型的 FORMAT?

【问题讨论】:

    标签: sql-server node.js sequelize.js


    【解决方案1】:

    实际上,我解决了这个问题,比我想象的要容易得多。

    userTime: {
        type: DataTypes.TIME,
        allowNull: true,
        get() {
          const userTime = this.getDataValue('userTime');
          if(userTime == null) return  userTime;
          const time = new Date(userTime);
          let hours = addZero(time.getUTCHours());
          let minutes = addZero(time.getUTCMinutes());
          let combinedTime = hours + ":" + minutes;
          return combinedTime;
        }
    }   
    function addZero(i) {
    if (i < 10) {
        i = "0" + i;
    }
    return i;
    }
    

    【讨论】:

    • 这将返回修改后的原始字段,我建议使用我的解决方案,因为它保持字段原样并返回另一个具有预期值的字段。
    • 我知道,这不是问它的正确地方,但你能帮我解决这个问题吗:stackoverflow.com/questions/47215961/… 我试着在文档中寻找这个,但找不到任何解决方案。
    • 我知道您必须为此提供关联,否则您必须自己进行原始查询。没有其他办法。
    【解决方案2】:

    我的建议是创建一个 getterMethods ,像 virtual field 一样工作,您将在每个查询中得到它。

    var User = sequelize.define('users',{
        userTime:{
            type: DataTypes.TIME    
        },
        name:{
            type: db.Sequelize.STRING,
            allowNull: false
        },
        image: {
            type: db.Sequelize.STRING,
            allowNull: true
        },
        .... // other fields
    },{
        getterMethods:{
            modifiedUserTime() {
                return moment(this.userTime); // modify the time as you want
            }
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-12
      • 1970-01-01
      • 1970-01-01
      • 2021-06-22
      • 2015-07-04
      • 2020-08-11
      • 1970-01-01
      • 2021-09-22
      相关资源
      最近更新 更多