14

Sequelize官网翻译十 —— Paranoid

 4 years ago
source link: https://zhuanlan.zhihu.com/p/125027110
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Sequelize官网翻译十 —— Paranoid

Sequelize也支持paranoid表。paranoid表是在被告之要删除记录时并不会真正的物理上删除,而是添加一个存有删除请求时间戳deletedAt的特殊字段。

paranoid表就是软删除而非硬删除机制的表。

把模型定义为paranoid

传递paranoid: true参数给模型定义中。paranoid要求必须启用时间戳,即必须传timestamps: true

也能把默认的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方法,但对于实例方法也是相同的

 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

Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK