在 Sequelize 中创建具有多个关联的实例

Creating instance with multiple associations in Sequelize

我有 NodeJS 作为后端,我的数据库是 MySql。 Sequelize 是我的 ORM。 在 Sequelize 5 中,我有几个 类:WorkOder、User(技工)、Customer、Client 和 ExpertiseOffice。 我的数据模型并不复杂,只有 1:1 个关系。一个 WorkOrder 有一个客户、一个客户和一个 ExpertiseOffice。

我使用 Postman 来测试我的 api。通过创建包含一些客户字段的工作单,创建了工作单,但没有创建客户。

我的关联文件如下所示:

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' });

WorkOrder 模型如下所示:

// 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;

在前端应用程序中,只需要非常有限的字段,因为前端用户可以稍后添加有关客户、客户等的信息。

目前,我的 WorkOrder 控制器与创建 workOrder 代码(无法正常工作)看起来像这样。

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);
    });
};

我的邮递员[=3​​5=]动作的本体是这样的:

{
  "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
}

如何创建带有关联数据(如客户或客户数据)的工单?创建的数据在开始时不完整,前端用户将添加更多数据以完成一个工单。

非常感谢您的阅读和帮助。 皮特

您可以将 child 模型包含在 parent sequelize 的创建方法中。只是你必须管理正确的命名,比如

如果您的 child 模特名称是 Custome,那么您的身材一定是这样的。

{
    //parent model colunm

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

在你的情况下你可以这样做。

  WorkOrder.create(req.body,{include:[Customer]})