简体   繁体   中英

How can I update multiple columns in sequelize.query

For now I update my table accounts with accountId and it's working perfectly.

return models.sequelize.query("UPDATE \"accounts\" " +
                                        "SET \"accountId\" = "+newAccount.id+" " +
                                        "WHERE \"accountId\" = "+oldAccount.id+";").spread(function(){
            return 'success';
        });

What if I want to change not only accountId, but, say, the date. How should I write it then? I've tried writing it with the comma

"SET \\"accountId\\" = "+ newAccount.id+",\\"date\\" + newAccount.date + " WHERE...

but that doesn't seem to work.

Appreciate your help.

UPDATE: in console I get this message [2015-10-25 16:42:00.909] [TRACE] main - Executing (default): UPDATE "accounts" SET "date" = Sun Oct 25 2015 16:42:00 GMT+0300 (MSK) WHERE "date" = Sun Oct 25 2015 16:41:53 GMT+0300 (MSK); but after that I don't get any 'success' message (data didn't change in db). May it happen because of data type? I have 'timestamp with time zone' in my postgresql database.

I guess, here can be the same problem

When you try to query by a date, you are sending over a JavaScript date object which gets converted into a string of the local time. PostgreSQL then rejects this due to invalid syntax both because the date doesn't get quoted and because it won't recognize the format.

Whenever possible, try not use raw queries when using Sequelize, because Sequelize can do all of the necessary serialization and deserialization for you. Your some issue could easily be done by writing this:

var Account = sequelize.define('account', {
  accountId: Sequelize.INTEGER,
  date: Sequelize.DATE
});

Account.update({
  accountId: newAccount.id,
  date: new Date()
}, {
  where: {
    accountId: oldAccount.id
  }
}).then(function() {
  callback('success');
});

If you really want to do this with a raw query, you should convert your date object into something that PostgreSQL can read. You could do this with the moment library for instance:

var moment = require('moment');

models.sequelize.query("UPDATE \"accounts\" " +
 "SET \"accountId\" = " + newAccount.id + ", " +
   "\"date\" = '" + moment().format('YYYY-MM-DD HH:mm:ss') + "' " +
 "WHERE \"accountId\" = " + oldAccount.id + ";").spread(function(){
 return 'success';
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM