node.js - 实现 SequelizeJS 软删除的问题
问题描述
我正在尝试在 SequelizeJS 中实现“软删除”。因此,我在模型中添加了“paranoid: true”,在迁移中添加了“deletedAt”列。我尝试使用另一个问题的答案,但由于版本不同,它不起作用。另外,我不确定我是否正确编写了控制器。网上没有那么多信息,所以我不确定如何检查我是否正确执行。我正在使用 Sequelize 5.3.0。这是我的模型:
'use strict';
module.exports = (sequelize, DataTypes) => {
const Properties = sequelize.define('Properties', {
name: {
allowNull: false,
type: DataTypes.STRING
}
}, {
timestamps: true,
paranoid: true
});
Properties.associate = function(models) {
// associations can be defined here
Properties.hasMany(models.Deals, {
foreignKey: 'id',
onDelete: 'CASCADE'
})
};
return Properties;
};
这是我的迁移:
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('Properties', {
id: {
allowNull: false,
primaryKey: true,
type: Sequelize.INTEGER,
autoIncrement: true
},
name: {
allowNull: false,
type: Sequelize.STRING
}
deletedAt: {
type: Sequelize.DATE
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('Properties');
}
};
我从官方文档中找到了这个解决方案,但这对我来说没有意义:
User.findAll({
include: [{
model: Tool,
where: { name: { [Op.like]: '%ooth%' } },
paranoid: false // query and loads the soft deleted records
}]
});
我的 getAllProperties 控制器:
getAllProperties: (req, res, next) => {
return Properties
.all()
.then(properties => res.status(200).json({ status: 'Retrieved all properties', properties }))
.catch(error => console.log(error));
}
我的 destroyProperty 控制器:
destroyProperty: (req, res, next) => {
const { id } = req.params;
return Properties
.findById(id)
.then(property => {
if (!property) {
return res.status(404).send({ message: 'Property not found' })
}
return property
.destroy()
.then(() => res.status(200).json({ status: 'Deleted one property', property }))
.catch(error => console.log(error));
})
}
解决方案
我发现,我的模型和迁移都很好,问题是我在做sequelize db:migrate:undo:all
and sequelize db:migrate
,但是 db 模式保持不变。所以,我做了sequelize db:drop
,sequelize db:create
然后它开始创建这个领域。另外,我更改了我的 getAllProperties 控制器:
getAllProperties: (req, res, next) => {
return Properties
.findAll({paranoid: false})
.then(properties => res.status(200).json({ status: 'Retrieved all properties', properties }))
.catch(error => console.log(error));
}
在我改变了这一切之后,它开始工作了。
推荐阅读
- php - 身份验证后重定向期间请求挂起
- css - css flex - 在 div 之间制造间隙
- mysql - SQL 计算表中的不同值,具有多种 Where 可能性
- reactjs - 使用 DrawerNavigator 时 this.props.navigation.goback() 无法正常工作
- c++ - 从 boost binary_iarchive 读取的数据不正确
- agda - 表示同态而不写出所有定律
- git - 当提交已经合并时,将提交重新设置到 master
- python - 在python中,如何在不同对象之间共享(引用)一个变量作为属性?
- node.js - 使用文本输入上传文件的最佳方式
- angular - 模板解析错误:不是已知元素