首页 > 解决方案 > 模型 A 未关联模型 B 续集错误

问题描述

我有以下问题,我有 2 个模型:客户端

module.exports = (sequelize, DataTypes) => {
const Client = sequelize.define('Client', {      
  first_name: DataTypes.STRING,
  last_name: DataTypes.STRING,
  phone: DataTypes.STRING,
  mobile_phone: DataTypes.STRING,
  email: DataTypes.STRING,                             
});

//creating association Client with Gender
Client.associate = function (models) {
  Client.hasOne(models.Gender, {     
       //     
  });
};


return Client; }

和性别:

module.exports = (sequelize, DataTypes) => {
const Gender = sequelize.define('Gender', {      
  name: DataTypes.STRING,                             
});

//creating association Gender with Employee
Gender.associate = function (models) {
  models.Gender.hasMany(models.Employee, {   
    //                         
  });
};

//creating association Gender with Client
Gender.associate = function (models) {
  models.Gender.belongsTo(models.Client, { 
    foreignKey: 'gender_id'                   
  });
};

return Gender; }

我的客户端控制器:

const { Client, Gender } = require('../models');

class ClientController {

  // Apresenta todos os resgistros do determinado Model
  async index (req, res) {
      const clients = await Client.findAll({});

      return res.status(200).json({
          status: 'ok',
          clients
      });
  }

  // Apresenta os atributos setados de um resgistro específico
  async show (req, res) {
      const client = await Client.findAll({
          attributes: ['id', 'first_name', 'last_name', 'phone', 'mobile_phone', 'email'],
          where: {
              id: req.params.id
          },
          include: [{
              model: Gender,                 
              attributes: [],

          }],
      });

      return res.status(200).json({
          status: 'ok',
          client
      });
  }

  // Cria e salva um resgistro do Model especificado
  async store (req, res) {
      const client = await Client.create(req.body);

      return res.status(201).json({
          status: 'created',
          client
      });
  }

  // Edita e salva um resgistro do Model especificado
  async update (req, res) {
      const { first_name, last_name, phone, mobile_phone, email } = req.body;

      const client = await Client.update({
          first_name: first_name,
          last_name: last_name,
          phone: phone,
          mobile_phone: mobile_phone,
          email: email

      }, {
          where: {
              id: req.params.id
          }
      });

      return res.status(200).json({
          status: 'updated',
          client
      });
  }

  // Exclui um resgistro do Model especificado
  async destroy (req, res) {
      await Client.destroy({
          where: {
              id: req.params.id
          }
      });

      return res.status(204).json({
          status: 'removed'
      });
  }
}

module.exports = new ClientController()

但以下返回给我:

节点 ./bin/www

api:server 监听端口 3000 +0ms (node:16328) UnhandledPromiseRejectionWarning: SequelizeEagerLoadingError: Gender is not associated to Client!在 Function._getIncludedAssociation (C:\SISTEMA-REACT-EXPRESS\api\node_modules\sequelize\lib\model.js:715:13) 在 Function._validateIncludedElement (C:\SISTEMA-REACT-EXPRESS\api\node_modules\sequelize\ lib\model.js:619:53) 在 options.include.options.include.map.include (C:\SISTEMA-REACT-EXPRESS\api\node_modules\sequelize\lib\model.js:516:37) 在 Array .map () 在 Function._validateIncludedElements (C:\SISTEMA-REACT-EXPRESS\api\node_modules\sequelize\lib\model.js:511:39) 在 Promise.try.then.then (C:\SISTEMA-REACT- EXPRESS\api\node_modules\sequelize\lib\model.js:1726:14) at tryCatcher (C:\SISTEMA-REACT-EXPRESS\api\node_modules\bluebird\js\release\util.js:16:23) at Promise . \SISTEMA-REACT-EXPRESS\api\node_modules\bluebird\js\release\async.js:15:14) at runCallback (timers.js:705:18) at tryOnImmediate (timers.js:676:5) at processImmediate ( timers.js:658:5) (node:16328) UnhandledPromiseRejectionWarning:未处理的承诺拒绝。此错误源于在没有 catch 块的情况下抛出异步函数内部,或拒绝未使用 .catch() 处理的承诺。(拒绝 id:1)(节点:16328)[DEP0018] DeprecationWarning:不推荐使用未处理的承诺拒绝。将来,未处理的 Promise 拒绝将使用非零退出代码终止 Node.js 进程。未处理的承诺拒绝。此错误源于在没有 catch 块的情况下抛出异步函数内部,或拒绝未使用 .catch() 处理的承诺。(拒绝 id:1)(节点:16328)[DEP0018] DeprecationWarning:不推荐使用未处理的承诺拒绝。将来,未处理的 Promise 拒绝将使用非零退出代码终止 Node.js 进程。未处理的承诺拒绝。此错误源于在没有 catch 块的情况下抛出异步函数内部,或拒绝未使用 .catch() 处理的承诺。(拒绝 id:1)(节点:16328)[DEP0018] DeprecationWarning:不推荐使用未处理的承诺拒绝。将来,未处理的 Promise 拒绝将使用非零退出代码终止 Node.js 进程。

Obs:在与数据透视表的n:m关系中,一切正常,有人可以帮助我吗?

标签: javascriptmysqlnode.jsexpresssequelize.js

解决方案


您正在用第二个关联覆盖您的第一个关联:

//creating association Gender with Employee
Gender.associate = function (models) {
  models.Gender.hasMany(models.Employee, {   
    //                         
  });
};

//creating association Gender with Client
Gender.associate = function (models) {
  models.Gender.belongsTo(models.Client, { 
    foreignKey: 'gender_id'                   
  });
};

只需将它们组合成一个:

//creating Gender associations
Gender.associate = function (models) {
  models.Gender.hasMany(models.Employee, {   
  models.Gender.belongsTo(models.Client, { 
    foreignKey: 'gender_id'                   
  });
};

推荐阅读