跳至主要内容
版本:v6 - 稳定版

偏执模式

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