2017-02-28 53 views
1

下面是我使用掛鉤,以更新兩個對象updatedAt列代碼:Sequelize:更新updatedAt手動

hooks: { 
       afterUpdate: (group, options, callback) => { 
        console.log("groudId " + groupId + " options " + options) 
       }, 
       afterCreate: (member, options, callback) => { 
        return new Promise((resolve, reject) => { 
         sequelize.models.Group.findOne({ 
          where: { 
           id: member.group_id 
          } 
         }).then((group) => { 
          if (group) { 
           var date = new Date(); 
           console.log("BEFORE group.updatedAt " + group.updatedAt) 
           group.dataValues.updatedAt = new Date() 
           console.log("CHANGED group.updatedAt " + group.updatedAt) 
           group.save().then((Group) => { 
            if (Group) { 
             console.log("UPDATED Group.updatedAt " + Group.updatedAt) 
             console.log("UPDATED group.updatedAt " + group.updatedAt) 
             resolve(Group) 
            } else { 
             console.log("NO GROUP Found") 
             return reject(group.id) 
            } 
           }).catch((error) => { 
            return (error) 
           }) 
          } else { 
           return reject(id) 
          } 
         }).catch((error) => { 
          return (reject) 
         }) 
        }) 
       } 

控制檯登錄:

BEFORE group.updatedAt Fri Feb 17 2017 17:36:00 GMT-0800 (PST) 
CHANGED group.updatedAt Tue Feb 28 2017 14:00:17 GMT-0800 (PST) 
UPDATED Group.updatedAt Tue Feb 28 2017 14:00:17 GMT-0800 (PST) 
UPDATED group.updatedAt Tue Feb 28 2017 14:00:17 GMT-0800 (PST) 
BEFORE group.updatedAt Fri Feb 17 2017 17:36:00 GMT-0800 (PST) 
CHANGED group.updatedAt Tue Feb 28 2017 14:00:19 GMT-0800 (PST) 
UPDATED Group.updatedAt Tue Feb 28 2017 14:00:19 GMT-0800 (PST) 
UPDATED group.updatedAt Tue Feb 28 2017 14:00:19 GMT-0800 (PST) 

雖然日誌,我在想什麼,顯示正確,爲什麼數據庫中的實際對象未更新爲新的updatedAt值?還是有更容易方式更新對象updatedAt列?

回答

0

Accodrding to the docs,您可以通過調用instance.set(key, value, [options])更新一個實例值,所以,你的情況應該是:

group.changed('updatedAt', true) 

這將標誌着updatedAt柱:

console.log("BEFORE group.updatedAt " + group.updatedAt) 
group.set('updatedAt', new Date()) 
console.log("CHANGED group.updatedAt " + group.updatedAt) 
group.save().then((Group) => { /* the other part of your code*/ }) 
+0

謝謝,我試過了,但那也行不通。事實上,它根本不會更新。以下是日誌:'BEFORE group.updatedAt Fri Feb 17 2017 17:36:00 GMT-0800(PST) CHANGED group.updatedAt Fri Feb 17 2017 17:36:00 GMT-0800(PST) UPDATED Group.updatedAt Fri Feb 17 2017 17:36:00 GMT-0800(PST) UPDATED group.updatedAt Fri Feb 17 2017 17:36:00 GMT-0800(PST)' – user1107173

0

以下工作過因爲髒,所以它會被更新。