偏執模式
Sequelize 支援偏執表格的概念。偏執表格是指當被告知刪除記錄時,它不會真正刪除它。而是將一個名為 deletedAt
的特殊欄位的值設定為該刪除請求的時間戳記。
這表示偏執表格執行記錄的軟刪除,而不是硬刪除。
將模型定義為偏執模式
若要將模型設定為偏執模式,您必須將 paranoid: true
選項傳遞給模型定義。偏執模式需要時間戳記才能運作(也就是說,如果您同時傳遞 timestamps: false
,它將無法運作)。
您也可以將預設欄位名稱(即 deletedAt
)變更為其他名稱。
class Post extends Model {}
Post.init(
{
/* attributes here */
},
{
sequelize,
paranoid: true,
// If you want to give a custom name to the deletedAt column
deletedAt: 'destroyTime',
},
);
刪除
當您呼叫 destroy
方法時,將會發生軟刪除
await Post.destroy({
where: {
id: 1,
},
});
// UPDATE "posts" SET "deletedAt"=[timestamp] WHERE "deletedAt" IS NULL AND "id" = 1
如果您真的想要硬刪除,而您的模型是偏執模式,您可以使用 force: true
選項強制執行
await Post.destroy({
where: {
id: 1,
},
force: true,
});
// DELETE FROM "posts" WHERE "id" = 1
上述範例使用靜態 destroy
方法作為範例(Post.destroy
),但所有方法都以相同的方式使用實例方法
const post = await Post.create({ title: 'test' });
console.log(post instanceof Post); // true
await post.destroy(); // Would just set the `deletedAt` flag
await post.destroy({ force: true }); // Would really delete the record
還原
若要還原軟刪除的記錄,您可以使用 restore
方法,該方法同時有靜態版本和實例版本
// Example showing the instance `restore` method
// We create a post, soft-delete it and then restore it back
const post = await Post.create({ title: 'test' });
console.log(post instanceof Post); // true
await post.destroy();
console.log('soft-deleted!');
await post.restore();
console.log('restored!');
// Example showing the static `restore` method.
// Restoring every soft-deleted post with more than 100 likes
await Post.restore({
where: {
likes: {
[Op.gt]: 100,
},
},
});
與其他查詢的行為
Sequelize 執行的每個查詢都會自動忽略軟刪除的記錄(當然,原始查詢除外)。
這表示,例如,findAll
方法將不會看到軟刪除的記錄,只會擷取未刪除的記錄。
即使您只是呼叫 findByPk
並提供軟刪除記錄的主鍵,結果也會是 null
,就像該記錄不存在一樣。
如果您真的想要讓查詢看到軟刪除的記錄,您可以將 paranoid: false
選項傳遞給查詢方法。例如
await Post.findByPk(123); // This will return `null` if the record of id 123 is soft-deleted
await Post.findByPk(123, { paranoid: false }); // This will retrieve the record
await Post.findAll({
where: { foo: 'bar' },
}); // This will not retrieve soft-deleted records
await Post.findAll({
where: { foo: 'bar' },
paranoid: false,
}); // This will also retrieve soft-deleted records