Updating instance with multiple associations in Sequelize

给你一囗甜甜゛ 提交于 2020-07-23 06:15:05

问题


I am able to create records in my MySQL DB with sequelize and NodeJS.

But now I am trying to update records in my Database.

I have NodeJS as backend and my DB is MySql. Sequelize is my ORM. In Sequelize 5, I have a couple of classes: WorkOder, User (mechanic), Customer, Client and ExpertiseOffice. My datamodel is not complex, there are only 1:1 relations. A WorkOrder has one customer, one Client and one ExpertiseOffice.

I use Postman to test my api's. With creating a WorkOrder with some Customer fields included the workOrder is created but not the Customer.

My associations file looks like this:

const User = require('../models/user');
const WorkOrder = require('../models/work-order');
const Customer = require('../models/customer');
const Client = require('../models/client');
const ExpertiseOffice = require('../models/expertise-office');

WorkOrder.belongsTo(User, { foreignKey: 'mechanicId' });
WorkOrder.belongsTo(Client, { foreignKey: 'clientId' });
WorkOrder.belongsTo(Customer, { foreignKey: 'customerId' });
WorkOrder.belongsTo(ExpertiseOffice, { foreignKey: 'expertiseOfficeId' });

The WorkOrder model looks like this:

// WORK-ORDER MODEL

const Customer = require('./customer');
const Client = require('./client');
const ExpertiseOffice = require('./expertise-office');
const User = require('./user');

const Sequelize = require('sequelize');

const sequelize = require('../util/database');

const WorkOrder = sequelize.define('workOrders', {
  id: {
    type: Sequelize.UUID,
    allowNull: false,
    primaryKey: true,
  },
  projectNumber: {
    type: Sequelize.INTEGER,
    allowNull: true,
  },
  dateInspection: {
    type: Sequelize.DATE,
    allowNull: true,
  },
  mechanicId: {
    type: Sequelize.UUID,
    allowNull: true,
    references: {
      // User belongsTo WorkOrder 1:1
      model: 'User',
      key: 'id',
    },
  },
  clientId: {
    // Opdrachtgever
    type: Sequelize.UUID,
    allowNull: true,
    references: {
      // Client belongsTo WorkOrder 1:1
      model: 'Client',
      key: 'id',
    },
  },
  customerId: {
    // klant
    type: Sequelize.UUID,
    allowNull: true,
    references: {
      // Customer belongsTo WorkOrder 1:1
      model: 'Customer',
      key: 'id',
    },
  },
  expertiseOfficeId: {
    type: Sequelize.UUID,
    allowNull: true,

    references: {
      // ExpertiseOffice belongsTo WorkOrder 1:1
      model: 'ExpertiseOffice',
      key: 'id',
    },
  },
  leakageReason: {
    type: Sequelize.STRING,
    allowNull: true,
  },
  status: {
    type: Sequelize.STRING,
    allowNull: true,
  },
  // Timestamps
  createdAt: Sequelize.DATE,
  updatedAt: Sequelize.DATE,
});

module.exports = WorkOrder;

In the front end application only very limited fields are required because the front end user can add information about the customer, client etc. on a later moment.

My WorkOrder controller with the updatre workOrder code (not working properly) is looking like this.

exports.updateWorkOrder = (req, res, next) => {
  console.log('####-in the updateWorkOrder endpoint!');
  const workOrder = req.body;
  console.log('####-put-workorder', workOrder);

  WorkOrder.update(
    workOrder,
    { where: { id: req.params.id } },
    { include: [User, Customer, Client, ExpertiseOffice] }
  )
    .then((result) => {
      if (result) {
        WorkOrder.findByPk(req.params.id).then((result) => {
          console.log('####--result', result);
          console.log('####-work-order updated!');
          res.status(200).json({
            message: 'Work order successfully updated!',
            data: result,
          });
        });
      }
    })
    .catch((err) => {
      console.log('error', err);
      res.status(500).json({
        message: 'An error occurred',
        err: err,
      });
    });
};

The workOrder data which is going into the update method looks like this:

####-in the updateWorkOrder endpoint!
####-put-workorder {
  id: '29d9795d-ef7f-418e-a479-340cb7ee5509',
  projectNumber: '123456',
  dateInspection: null,
  followupInspection: null,
  clientPresent: null,
  mechanicId: null,
  clientId: '2c611177-48f6-48d2-a2d0-e7f6a93cc16b',
  customerId: 'd53f56c7-9954-4e52-b8e2-de4d28229caf',
  expertiseOfficeId: null,
  leakageReason: 'issue with roof',
  visibleWaterDamage: null,
  visibleWaterDamagePeriod: null,
  buildingType: null,
  renovatedYear: null,
  status: null,
  createdAt: '2020-07-04T07:24:28.000Z',
  updatedAt: '2020-07-04T07:25:03.000Z',
  user: null,
  customer: {
    id: 'd53f56c7-9954-4e52-b8e2-de4d28229caf',
    name: 'Customer One',
    contactPerson: null,
    companyName: null,
    street: 'Street',
    houseNumber: '1',
    houseNumberExt: null,
    zipCode: '91111',
    city: 'LA',
    phoneNumber: null
  },
  client: {
    id: '2c611177-48f6-48d2-a2d0-e7f6a93cc16b',
    name: 'Roof Inspectors',
    contactPerson: null,
    email: null,
    phoneNumber: 'Roof Inspectors',
    street: null,
    houseNumber: null,
    houseNumberExt: null,
    zipCode: null,
    city: null,
    attribute: null
  },
  expertiseOffice: null
}

This is the correct updated information from the front end.

Now I don't get an error message from sequelize but the record is not updated. The spooled result looks like this:

####--result workOrders {
  dataValues: {
    id: '29d9795d-ef7f-418e-a479-340cb7ee5509',
    projectNumber: '123456',
    dateInspection: null,
    followupInspection: null,
    clientPresent: null,
    mechanicId: null,
    clientId: '2c611177-48f6-48d2-a2d0-e7f6a93cc16b',
    customerId: 'd53f56c7-9954-4e52-b8e2-de4d28229caf',
    expertiseOfficeId: null,
    leakageReason: 'issue with roof',
    visibleWaterDamage: null,
    visibleWaterDamagePeriod: null,
    buildingType: null,
    renovatedYear: null,
    status: null,
    createdAt: 2020-07-04T07:24:28.000Z,
    updatedAt: 2020-07-04T08:06:47.000Z
  },
  _previousDataValues: {
    id: '29d9795d-ef7f-418e-a479-340cb7ee5509',
    projectNumber: '123456',
    dateInspection: null,
    followupInspection: null,
    clientPresent: null,
    mechanicId: null,
    clientId: '2c611177-48f6-48d2-a2d0-e7f6a93cc16b',
    customerId: 'd53f56c7-9954-4e52-b8e2-de4d28229caf',
    expertiseOfficeId: null,
    leakageReason: 'issue with roof',
    visibleWaterDamage: null,
    visibleWaterDamagePeriod: null,
    buildingType: null,
    renovatedYear: null,
    status: null,
    createdAt: 2020-07-04T07:24:28.000Z,
    updatedAt: 2020-07-04T08:06:47.000Z
  },
  _changed: {},
  _modelOptions: {
    timestamps: true,
    validate: {},
    freezeTableName: false,
    underscored: false,
    paranoid: false,
    rejectOnEmpty: false,
    whereCollection: { id: '29d9795d-ef7f-418e-a479-340cb7ee5509' },
    schema: null,
    schemaDelimiter: '',
    defaultScope: {},
    scopes: {},
    indexes: [],
    name: { plural: 'workOrders', singular: 'workOrder' },
    omitNull: false,
    sequelize: Sequelize {
      options: [Object],
      config: [Object],
      dialect: [MysqlDialect],
      queryInterface: [QueryInterface],
      models: [Object],
      modelManager: [ModelManager],
      connectionManager: [ConnectionManager],
      importCache: {}
    },
    hooks: {}
  },
  _options: {
    isNewRecord: false,
    _schema: null,
    _schemaDelimiter: '',
    raw: true,
    attributes: [
      'id',
      'projectNumber',
      'dateInspection',
      'followupInspection',
      'clientPresent',
      'mechanicId',
      'clientId',
      'customerId',
      'expertiseOfficeId',
      'leakageReason',
      'visibleWaterDamage',
      'visibleWaterDamagePeriod',
      'buildingType',
      'renovatedYear',
      'status',
      'createdAt',
      'updatedAt'
    ]
  },
  isNewRecord: false
}

Can anybody please help me? I have no clue why the records is not updated. Many thanks in advance. Pete

来源:https://stackoverflow.com/questions/62726830/updating-instance-with-multiple-associations-in-sequelize

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!