0

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.

At the moment my WorkOrder controller with the create workOrder code (not working properly) is looking like this.

exports.createWorkOrder = (req, res, next) => {
  console.log('####-in the createWorkOrder endpoint');
  console.log('####-LC-body', req.body);

  const id = req.body.id;
  const projectNumber = req.body.projectNumber;
  const dateInspection = req.body.dateInspection;
  const followupInspection = req.body.followupInspection;
  const clientPresent = req.body.clientPresent;
  const MechanicId = req.body.mechanicId;
  const ClientId = req.body.clientId;
  const CustomerId = req.body.customerId;
  const expertiseOfficeId = req.body.expertiseOfficeId;
  const leakageReason = req.body.leakageReason;
  const visibleWaterDamage = req.body.visibleWaterDamage;
  const visibleWaterDamagePeriod = req.body.visibleWaterDamagePeriod;
  const buildingType = req.body.buildingType;
  const renovatedYear = req.body.renovatedYear;
  const status = req.body.Status;

  WorkOrder.create({
    id: id,
    projectNumber: projectNumber,
    dateInspection: dateInspection,
    followupInspection: followupInspection,
    clientPresent: clientPresent,
    mechanicId: MechanicId,
    clientId: ClientId,
    customerId: CustomerId,
    expertiseOfficeId: expertiseOfficeId,
    leakageReason: leakageReason,
    visibleWaterDamage: visibleWaterDamage,
    visibleWaterDamagePeriod: visibleWaterDamagePeriod,
    buildingType: buildingType,
    renovatedYear: renovatedYear,
    status: status,
  })
    .then((result) => {
      console.log('####-work-order create!');
      res.status(200).json({
        message: 'Work order successfully created!',
        data: result,
      });
      // return res.json(result);
    })
    .catch((err) => {
      console.log('error', err);
    });
};

The body of my postman POST action is this:

{
  "id": "1116d911-b4fd-4ce5-9541-0a9efd3b6c98",
  "projectNumber": 1002,
  "dateInspection": null,
  "mechanicId": null,
  "ClientId": null,
  "CustomerId":"2226d911-b4fd-4ce5-9541-0a9efd3b6c98",
  "ExpertiseOfficeId":null,
  "leakageReason": "Test reden",
  "status": "Open",
  "user": null,
  "customer": {
    "id": "2226d911-b4fd-4ce5-9541-0a9efd3b6c98",
    "name": "Test naam customer",
    "companyName": null,
    "contactPerson": null,
    "email": null,
    "street": "test adres",
    "houseNumber": "1",
    "houseNumberExt": "",
    "zipCode": "1111AA",
    "city": "Amsterdam",
    "phoneNumber": null
  },
  "client": null,
  "expertiseOffice": null
}

How can I create a workOrder with it's associated data (like Customer or Client data)? The created data is at start not complete, the front end users will add more data to complete a work order along the way.

Many thanks for reading and for your help. Pete

PeteBaser
  • 263
  • 1
  • 5
  • 15

1 Answers1

1

you can include your child model with parent create method of sequelize . just you have to manage proper naming like

if your child model name is Custome than your body must be like this .

{
    //parent model colunm

    "Customer":{
        // customer model column names
    }
}

in your case you can do like this .

  WorkOrder.create(req.body,{include:[Customer]})
Arpit Vyas
  • 2,118
  • 1
  • 7
  • 18
  • 3
    Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – Mark Rotteveel Jun 21 '20 at 12:46
  • Dear Vyas Arpit, thank you very much for your reply. this: WorkOrder.create(req.body,{include:[Customer]}) did the trick!! – PeteBaser Jun 22 '20 at 06:46
  • @PeteBaser happy to have helped :) – Arpit Vyas Jun 22 '20 at 06:50
  • Hello @VyasArpit, I have asked a question about the update flow of the same workOrder: https://stackoverflow.com/questions/62726830/updating-instance-with-multiple-associations-in-sequelize, is it possible you can help me with that too? Many thanks.. Pete – PeteBaser Jul 05 '20 at 04:54