SequelizeJS,这是使用此模型创建此JSON结果的最佳方法

时间:2019-07-03 12:37:52

标签: node.js json sequelize.js

我想要这个结果,但是,用这种方法做起来太复杂了。有一种使用Sequelize创建此结果的更好方法。使用sequelize查询工具汇总来自不同表的结果,在JPA上,我唯一要做的就是用联接表注释并传递列ad invese列值。

[
    {
        "id": 1,
        "codemp": "999",
        "nome": "A3 Infortech",
        "limiteInstancias": "10",
        "instancias": []
    },
    {
        "id": 2,
        "codemp": "92",
        "nome": "Endovideo",
        "limiteInstancias": "20",
        "instancias": [
            {
                "id": 198211,
                "ipLocal": "40.0.10.11",
                "ipExterno": "187.33.230.106",
                "hostname": "FATURAMENTO-PC",
                "dataCriacao": "2019-07-01T21:40:29.000Z"
            }
        ]
    },
    {
        "id": 6,
        "codemp": "103",
        "nome": "SOS Otorrino",
        "limiteInstancias": "999",
        "instancias": [
            {
                "id": 199127,
                "ipLocal": "192.168.11.101",
                "ipExterno": "000.000.000.000",
                "hostname": "Guiche3-PC",
                "dataCriacao": "2019-07-01T21:40:32.000Z"
            },
            {
                "id": 199164,
                "ipLocal": "192.168.25.209",
                "ipExterno": "000.000.000.000",
                "hostname": "Consultorio06",
                "dataCriacao": "2019-07-01T21:40:29.000Z"
            }
        ]
    },
    {
        "id": 15,
        "codemp": "162",
        "nome": "Clinica Vida e Saude",
        "limiteInstancias": "10",
        "instancias": [
            {
                "id": 199774,
                "ipLocal": "192.168.56.1",
                "ipExterno": "000.000.000.000",
                "hostname": "ALEXANDRELEAL",
                "dataCriacao": "2019-07-01T21:40:28.000Z"
            }
        ]
    }
]

我有以下代码:

Empresa模型

module.exports = (sequelize, DataTypes) => {
  const empresa = sequelize.define("empresa", {
      id: {
          type: DataTypes.BIGINT(20),
          primaryKey: true,
          field: "id"
      },
      codemp: {
          type: DataTypes.INTEGER,
          field: "codemp"
      },
      nome: {
          type: DataTypes.STRING,
          field: "nome"
      },
      limiteInstancias: {
          type: DataTypes.INTEGER,
          field: "limite_instancias"
      }
  }, {
      timestamps: false,
      freezeTableName: true,
      tableName: "empresa"
  });

    empresa.associate = (db) => {
        console.log(db);
        empresa.hasMany(db.instanciaEmpresa, {foreignKey: "id_empresa"});
    };
  return empresa;
};

Instancia模型

module.exports = (sequelize, DataTypes) => {
    const instancia = sequelize.define("instancia", {
        id: {
            type: DataTypes.BIGINT(20),
            primaryKey: true,
            field: "id"
        },
        ipLocal: {
            type: DataTypes.STRING,
            field: "ip_local"
        },
        ipExterno: {
            type: DataTypes.STRING,
            field: "ip_externo"
        },
        hostname: {
            type: DataTypes.STRING,
            field: "hostname"
        },
        dataCriacao: {
            type: DataTypes.DATE,
            field: "data_criacao"
        },

    }, {
        timestamps: false,
        freezeTableName: true,
        tableName: "instancia"
    });

    instancia.associate = (db) => {
        console.log(db);
        instancia.belongsTo(db.empresa, {foreignKey: "id_instancia"});
    };
    return instancia;
};

InstanciaEmpresa模型

module.exports = (sequelize, DataTypes) => {
  const instanciaEmpresa = sequelize.define("instancia_empresa", {
      idEmpresa: {
          type: DataTypes.BIGINT(20),
          primaryKey: true,
          field: "id_empresa"
      },
      idInstancia: {
          type: DataTypes.BIGINT(20),
          primaryKey: true,
          field: "id_instancia"
      },
  }, {
      timestamps: false,
      freezeTableName: true,
      tableName: "instancia_empresa"
  });

  return instanciaEmpresa;
};

我的数据库图。 A picture of my database diagram 我的回复代码

const db = require("../config/db.config");
const empresa = db.empresa;
const instancia = db.instancia;
const instanciaEmpresa = db.instanciaEmpresa;

const empressaResult = [];

module.exports = {
    async getAll(req, res) {
        return res.send(await getAllEmpresa());
    }
};

async function getAllEmpresa() {
    //Recover all companies from the table
    let empresaList = await empresa.findAll({raw: true});

    //I browse the array of companies to retrieve the instances associated with the company
    for(let i = 0; i < empresaList.length; i++){
        //Create the atribute Instancias[]
        empresaList[i].instancias = [];
        //I retrieve the list of associated instances in the InstanciaEmpresa table
        let instanciasEmpresa = await instanciaEmpresa.findAll({where: {"id_empresa": empresaList[i].id}, raw: true});
        //Verify if existes any item of InstanciaEmpresa
        if(instanciasEmpresa.length > 0){
            //If there is a run through list of instances
            for(let j = 0; j < instanciasEmpresa.length; j++){
                //I retrieve the Instancia in the database and add it to the company Instancias list
                let inst = await instancia.findByPk(instanciasEmpresa[j].idInstancia, {raw: true});
                empresaList[i].instancias.push(inst);
            }
        }
        //I add the company with the instances in a result list;
        empressaResult.push(empresaList[i]);
    }
    return empressaResult;
}

1 个答案:

答案 0 :(得分:0)

您可以使用include选项对表进行联接。

然后您的代码看起来像

const empresaList = await empresa.findAll({
  raw: true,
  include: [
    {
      model: instancias,
      required: false, // left join, `true` means inner join.
    }
  ]
});

如您所见,您可以将{ model, required }数组传递到include选项。

如果要进行内部联接,可以将required设置为true,否则将进行左联接。

---添加---

SequelizeEagerLoadingError: instancia is not associated to empresa表示您没有在数据库初始化时调用关联函数。

您可以在db.js中编写如下的帮助函数。

addAssociations(name) {
  if (this[name].associate) {
      this[name].associate(this);
    }
  }
}

并像使用它

/*
 * this.models = [
 *   {
 *     name: 'instancias',
 *     model: instancias,
 *   },
 *   ... and many more
 * ]
 */
this.models.forEach((value) => {
  this.addAssociations(value.name);
});