首页 > 解决方案 > 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 与某个对象进行比较。

标签: mysqlnode.jssequelize.js

解决方案


推荐阅读