Sequelize 保存前计算值 [英] Sequelize calculate value before saving

查看:42
本文介绍了Sequelize 保存前计算值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在保存模型之前以小时为单位计算差异.我已经尝试过 beforeUpdate(和其他钩子),但从未计算过该字段.我也试过 set: 选项,但这也不起作用.

I want to calculate the difference in hours before saving a model. I have tried beforeUpdate (and other hooks), but the field is never calculated. I have also tried the set: option, but that doesn't work either.

我必须填写started_at"和ended_at".如果 end_at 不为空,则计算差异并保存到字段小时.

I have to fields 'started_at' and 'ended_at'. If ended_at is not null, then calc difference and save to field hours.

我试过了:

hours: {
      type: DataTypes.DECIMAL(10,2),
      allowNull: true,
      set: function(){
        var duration = 0;
        if(this.ended_at){
          var Start = moment(this.started_at);
          var End = moment(this.ended_at);
          duration = End.diff(Start, 'hours', true);   
        }
        this.setDataValue('hours', duration);
      }
    },

我已经尝试过:

beforeCreate: function(travel_log, options, fn){
        if(travel_log.ended_at){
          var Start = moment(travel_log.started_at);
          var End = moment(travel_log.ended_at);
          travel_log.hours = End.diff(Start, 'hours', true);
        }
        fn(null, travel_log)
      },

没有任何成功.该文档也不是很有帮助.有人可以帮忙吗?谢谢

without any success. The documentation isn't really helpful either. Can anybody help? Thx

推荐答案

InstanceMethods are required...

InstanceMethods are needed...

instanceMethods: {
      calcHours: function(started_at,ended_at){
        var duration = 0;
        if(ended_at){
          var Start = moment(started_at);
          var End = moment(ended_at);
          var duration = End.diff(Start, 'hours', true);

        }
        return duration;
      }
    },

所以在钩子中:

beforeCreate: function(travel_log, options, fn){
        travel_log.hours = travel_log.calcHours(travel_log.started_at,travel_log.ended_at);
        fn(null, travel_log)
      },

这篇关于Sequelize 保存前计算值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆