(三)sequelize postgres增删改

build创建实例

let account = Account.build({
    id: Date.now(),
    account: '4619test',
    password: '4619test'
});

console.log(account);   //account为对象实例

create保存数据到数据库

Account.create({
    id: Date.now(),
    account: '4619test',
    password: '4619test'
}).then(account => {
    console.log(account);   //保存成功后返回对象实例
}, err => {
    console.log(err);
});

//等同于
 Account.build({
    id: Date.now(),
    account: '4619test',
    password: '4619test'
  }).save().then(account => {
    console.log(account);
  }, err => {
    console.log(err);
  });

bulkCreate批量创建数据到数据库

Executing (default): INSERT INTO "account" ("id","account","password") VALUES (1528276108795,'4619test','4619test'),(1528276108895,'4619test1','4619test1');

Account.bulkCreate([{
    id: Date.now() - 100,
    account: '4619test',
    password: '4619test'
}, {
    id: Date.now(),
    account: '4619test1',
    password: '4619test1'
}]).then(res => {
    console.log(res);  //返回值为实例数组
}, err => {
    console.log(err);
});

destory删除数据

//实例对象删除
Account.findById('1528273928488').then(row => {
    return row.destroy(); //row为实例,要先判断是否为null
}).then(() => {
    //删除成功,返回空数组,不接收
});

//模型根据条件删除(多条处理)
Account.destroy({
    where: {           //各种条件,符合就删除
        id: 'test7'
    }
}).then(res => {
    console.log(res);  //返回影响条数
}, err => {
    console.log(err);
});

update更新数据

Executing (default): UPDATE "account" SET "account"='update' WHERE "id" = '1528276108795'

//修改数据放在方法中,实例对象更新
Account.findById('1528276108795').then(row => {
    return row.update({
        account: 'update'
    });
}).then(res => {
    console.log(res); //返回修改后的实例对象
}, err => {
    console.log(err);
});

Executing (default): UPDATE "account" SET "account"='461912' WHERE "password" IN ('4619test', '4619test1')

//模型根据条件更新(多条处理)
Account.update({
    account: '461912'
}, {
    where: {
        password: ['4619test', '4619test1']
    }
}).then(res => {
    console.log(res);  //[2]
}, err => {
    console.log(err);
});

save更新数据

//需要先赋值后修改
Account.findById('1528276108795').then(row => {
    row.account = 'save';
    return row.save();
}).then(res => {
    console.log(res); //返回修改后的实例对象
}, err => {
    console.log(err);
});

sequelize Instances

转载于:https://www.cnblogs.com/chenmengyuan/p/9083032.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值