mysql - Sequelize 更新 HasMany 关系
问题描述
我想更新 hasMany 关系的行,我有一个表 InRoutes 可以有很多 InRouteDetails,所以当我更新 InRoute 时我还需要更新它的详细信息,可能会发生三种情况,删除一个详细信息,更新一个详细信息并添加详细信息。
当我尝试使用 setInRouteDetails 进行更新但由于某种原因他试图获得一个等于给我此错误的对象的 InRouteDetail:截断不正确的 DOUBLE 值:'[object Object]'
这是我的模型:
export default (sequelize, DataType) => {
const InRoutes = sequelize.define('InRoutes', {
id: {
type: DataType.INTEGER,
primaryKey: true,
autoIncrement: true,
},
name: {
type: DataType.STRING,
allowNull: false,
validate: {
notEmpty: true,
},
},
description: {
type: DataType.TEXT,
allowNull: true,
},
createdBy: {
type: DataType.STRING,
allowNull: true,
},
updatedBy: {
type: DataType.STRING,
allowNull: true,
},
}, {
classMethods: {
associate: (models) => {
InRoutes.hasMany(models.InRoutesDetails, {
foreignKey: 'InRouteId',
as: 'InRouteDetails',
onDelete: 'CASCADE',
});
InRoutes.belongsTo(models.Trunks, {
foreignKey: 'trunkId',
as: 'TrunkId',
onDelete: 'CASCADE',
});
},
},
});
return InRoutes;
};
这是我尝试用他的关联“InRouteDetails”更新“InRoute”的地方:
async update(data, params, updatedBy) {
data.updatedBy = updatedBy.username;
try {
const inRoute = await this.InRoutes.findOne({ where: params });
const teste = [{
id: 2,
mask: '89',
remove: 4,
add: '3',
destinationType: 'callback',
destination: 2,
InRouteId: 2,
}];
await inRoute.addInRouteDetails(teste);
await inRoute.update(data);
return defaultResponse(inRoute);
} catch (error) {
return errorResponse(error.message, HttpStatus.UNPROCESSABLE_ENTITY);
}
}
这在控制台上给了我这个结果:
Executing (default): UPDATE `InRoutesDetails` SET `InRouteId`=?,`updatedAt`=? WHERE `id` IN ('[object Object]')
他试图将 id 与某个对象进行比较。
解决方案
推荐阅读
- node.js - 在 Node.js 中验证 Azure idToken
- c++ - 编译时检查 trait 特化是否有唯一的 id
- angular - 无法从获取请求中获取数据
- javascript - 我在哪里放置标题(chart.js)?
- google-analytics - 如何将事件链接并提取到谷歌分析中的会话 ID?
- laravel - 如何排队 Laravel 5.7“电子邮件验证”电子邮件发送
- javascript - 单击窗口以在跨度上添加类
- wordpress - WordPress woo commerce 按品牌获取产品
- jenkins - 在 Jenkins 中获取变量的结构
- java - ubuntu更新后tomcat 8停止工作