📅  最后修改于: 2023-12-03 15:22:11.224000             🧑  作者: Mango
在使用sequelize进行数据库操作时,更新某一行或某一列的数据是经常会遇到的需求。本文将介绍如何使用find方法来更新数据库表的某列数据。
const Sequelize = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password', {
host: 'localhost',
dialect: 'mysql'
});
const User = sequelize.define('user', {
firstName: {
type: Sequelize.STRING
},
lastName: {
type: Sequelize.STRING
},
age: {
type: Sequelize.INTEGER
}
});
User.find({
where: {
id: 1
}
}).then(user => {
user.age = 30;
user.save();
});
User.find({
where: {
id: 1
}
}).then(user => {
user.age = 30;
user.save();
});
const Sequelize = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password', {
host: 'localhost',
dialect: 'mysql'
});
const User = sequelize.define('user', {
firstName: {
type: Sequelize.STRING
},
lastName: {
type: Sequelize.STRING
},
age: {
type: Sequelize.INTEGER
}
});
User.sync({force: true}).then(() => {
return User.create({
firstName: 'John',
lastName: 'Doe',
age: 29
});
}).then(() => {
User.find({
where: {
id: 1
}
}).then(user => {
user.age = 30;
user.save();
});
});
以上代码会将id等于1的行的age字段更新为30。
使用find方法可以很方便地查询出要更新的行数据,然后通过给某一列重新赋值再调用save方法,即可更新表中某一列的数据。