sequelized的增删改
增
使用模型的build方法新增
不调用ins.save(),不会执行SQL语句,还可以通过ins更改属性。
1 2 3 4 5 6 7 8 9 10 11 12
| const Admin = require('./models/Admin');
const ins = Admin.build({ loginId: 'xyq', loginPwd: '123456', name: '谢永强' });
ins.save().then(() => { console.log('新增成功!') })
|
使用模型的create方法新增
异步函数。
相当于执行完build后再执行ins.save()。
1 2 3 4 5 6 7 8 9 10 11
| const Admin = require('./models/Admin');
Admin.create({ loginId: 'hsz', loginPwd: '123', name: '筱' }).then(() => { console.log('新增成功!') })
|
删除
先得到实例再删除
会执行两条SQL语句,一条查询,一条删除。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
async function(adminId) {
const ins = await Admin.findByPk(adminId);
if (ins) { ins.destroy(); } else { console.log('管理员不存在!') }
|
通过模型调用destory方法删除
只会执行一条SQL语句。
通过where来匹配要删除的数据
1 2 3 4 5 6 7 8 9 10 11
|
async function(adminId) { Admin.destroy({ where: { id: adminId, } }) }
|
修改
通过得到实例再更新数据
1 2 3 4 5 6 7 8 9 10
|
async function(id, adminObj) { const ins = await Admin.findByPk(id); ins.loginId = adminObj.loginId; ins.save(); }
|
通过模型中update方法来更新
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
exports.updateAdmin = async function(id, adminObj) { await Admin.update(adminObj, { where: { id, } })
}
|