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
.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With