问题
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.
I have to fields 'started_at' and 'ended_at'. If ended_at is not null, then calc difference and save to field hours.
I have tried:
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);
}
},
And I have tried:
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
回答1:
As I mention in the comment I'm not sure of what you want, but you can create an instance, change the variables of the instance. For example, if you have a model Task:
var task = Task.build();
task.hours = CalcHoursExample();
task.save();
Hope this helps
回答2:
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;
}
},
So in the hooks:
beforeCreate: function(travel_log, options, fn){
travel_log.hours = travel_log.calcHours(travel_log.started_at,travel_log.ended_at);
fn(null, travel_log)
},
来源:https://stackoverflow.com/questions/29183093/sequelize-calculate-value-before-saving