Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update only one row in sequelize

I am using Sequelize as ORM along with express.js Below is my minimalistic table structure.

Id  status          phone

1     0             09620701828
2     0             09620701828

Now when an api request is to make on an end-point then I have to update status for last id belonging to a particular phone that I am getting from request. Raw MySql query for which will be UPDATE table SET status=1 where phone='09620701828' ORDER BY id DESC LIMIT 1;

How I can achieve the same using Sequelize update method. Below is what I have tried

models.customerLeadFeedback.update(
    {status: 1},
    { 
        where: {phone : '09620701828'},
        order: [['id', 'DESC']],
        limit : 1

    }).then(function () {
        res.sendStatus(200);
    })`

But order by clause is not working for above and updating status for id 1. Can anyone help me with this without using raw query in sequelize.

like image 767
vinit payal Avatar asked Nov 03 '16 14:11

vinit payal


People also ask

How do I update multiple rows using Sequelize?

While Sequelize doesn't provide a bulkUpdate() method, both update() and bulkCreate() methods allow you to update multiple rows with a single method. When you need to update multiple rows with different values, you can use the bulkCreate() method.

How do you write a update query in Sequelize?

update query with select sequelize provide option update query after selection done, like first select some data using findOne() after update record using save() understand with example. user. first_name = "infinitbility"; user.

How do I delete a row in Sequelize?

To delete rows of data from your SQL table using Sequelize, you need to use the provided destroy() method. The destroy() method can be called from any Model or instance of your Model to delete rows from your table.


1 Answers

It would appear that Sequelize'sModel#update function doesn't support ordering - see the docs at http://sequelize.readthedocs.io/en/v3/api/model/#updatevalues-options-promisearrayaffectedcount-affectedrows

If you really want to target the row by ordering, you could fetch the row first, then update it:

models.customerLeadFeedback.findOne(
  {status: 1},
  { 
    where: {phone : '09620701828'},
    order: [['id', 'DESC']]
}).then(function (record) {
  return record.update({status: 1});
}).then(function (record) {
    res.sendStatus(200);
});

It's less efficient, using two queries instead of one, but currently looks like your only option if you don't want to use raw queries.

like image 169
Tom Jardine-McNamara Avatar answered Sep 23 '22 02:09

Tom Jardine-McNamara