Sequelize之Model实例

Model实例

model就是个ES6的class。model的每个实例都是这个model的一个对象,映射到数据库表中的一行。

创建一个Model实例

尽管model是个类。但是不能直接通过new创建实例,应该通过build方法。

const jane = User.build({ name: 'Jane' })

build方法是个同步事件,调用build方法并不会创建数据库表中的一行记录。仅仅是创建了一个能映射到数据库表的一行的数据对象。如果要保存到数据库中,需要调用save方法

await jane.save();

create方法

Sequelize提供了一个create方法,结合了build和save方法。即创建一个对象并保存到数据库中。

const jane = await User.create({ name: "Jane" });

实例打印

如果直接使用console.log输出实例,会输出很多杂乱的东西。因此可以使用.toJSON或者JSON.stringify方法输出实例。

const jane = await User.create({ name: "Jane" });
// console.log(jane); // Don't do this
console.log(jane.toJSON()); // This is good!
console.log(JSON.stringify(jane, null, 4)); // This is also good!

实例的更新

对实例字段

const jane = await User.create({ name: "Jane" });
console.log(jane.name); // "Jane"
jane.name = "Ada";
// the name is still "Jane" in the database
await jane.save();
// Now the name was updated to "Ada" in the database!

的所有更新操作,最后都需要调用save方法,才能将更新同步到数据库表中。

实例的删除

调用destroy方法删除一个实例,这个会直接删除数据库表中对应的数据

const jane = await User.create({ name: "Jane" });
console.log(jane.name); // "Jane"
await jane.destroy();
// Now this entry was removed from the database

实例的重载

可以通过调用reload方法从数据库中重新加载数据。

const jane = await User.create({ name: "Jane" });
console.log(jane.name); // "Jane"
jane.name = "Ada";
// the name is still "Jane" in the database
await jane.reload();
console.log(jane.name); // "Jane"

调用reload会生成一个SELECT查询,从而获取数据库表中最新的数据。

仅保存指定字段

调用save方法时,如果传入包含列名的数组,那么只会保存指定的列的数据到数据库中。有点类似于SQL的update语句

const jane = await User.create({ name: "Jane" });
console.log(jane.name); // "Jane"
console.log(jane.favoriteColor); // "green"
jane.name = "Jane II";
jane.favoriteColor = "blue";
await jane.save({ fields: ['name'] });
console.log(jane.name); // "Jane II"
console.log(jane.favoriteColor); // "blue"
// The above printed blue because the local object has it set to blue, but
// in the database it is still "green":
await jane.reload();
console.log(jane.name); // "Jane II"
console.log(jane.favoriteColor); // "green"

save方法的更新机制

save方法内部做了优化,只会更新真正变更了的字段。这就意味着,如果没有任何改变就调用save方法。Sequelize会知道这个save是多余的,不会进行任何操作,不会产生任何数据库查询操作。

为了提高性能,如果只是更新几个字段的值,那么调用save方法时,只有这几个字段会传入UPDATE查询。

整数数值的增加或减少

为了解决数值的增加/减少所带来的并发问题,Sequelize提供了increment和decrement实例方法。

const jane = await User.create({ name: "Jane", age: 100 });
const incrementResult = await user.increment('age', { by: 2 });
// Note: to increment by 1 you can omit the `by` option and just do `user.increment('age')`

也可以一次增加多个字段的值

const jane = await User.create({ name: "Jane", age: 100, cash: 5000 });
await jane.increment({
  'age': 2,
  'cash': 100
});

// If the values are incremented by the same amount, you can use this other syntax as well:
await jane.increment(['age', 'cash'], { by: 2 });

decrement操作和increment相同

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章