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相同