简体   繁体   English

SequelizeJS HasOne关联错误

[英]SequelizeJS HasOne association error

I am relatively new to NodeJS and SequelizeJS and am facing a hasOne issue with a query I am building and I'd like to know your thoughts about this issue to find out where I gone wrong and the correct way to implement this query. 我对NodeJS和SequelizeJS相对较新,并且正在构建一个查询时hasOne问题,我想知道您对这个问题的想法,以找出我出了问题的地方以及实现此查询的正确方法。

Association Here 这里的协会

The models where generated using sequelize-auto (pg-hstore). 使用sequelize-auto(pg-hstore)生成的模型。

Bloco Model: Bloco型号:

module.exports = function(sequelize, DataTypes) {
  return sequelize.define('bloco_condominio', {
    id_bloco: {
      type: DataTypes.INTEGER,
      allowNull: false,
      autoIncrement: true,
      primaryKey: true
    },
    id_condominio: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'condominio',
        key: 'id_condominio'
      }
    },
    nm_bloco: {
      type: DataTypes.STRING,
      allowNull: true
    },
    ic_status: {
      type: DataTypes.STRING,
      allowNull: false,
      defaultValue: "A"
    }
  }, {
    tableName: 'bloco_condominio'
  });
};

Apartamento Model: 公寓型号:

module.exports = function(sequelize, DataTypes) {
  return sequelize.define('apartamento', {
    id_apartamento: {
      type: DataTypes.INTEGER,
      allowNull: false,
      autoIncrement: true,
      primaryKey: true
    },
    id_condominio: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'condominio',
        key: 'id_condominio'
      }
    },
    nu_apto: {
      type: DataTypes.STRING,
      allowNull: true
    },
    id_bloco: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: {
        model: 'bloco_condominio',
        key: 'id_bloco'
      }
    },
    ic_status: {
      type: DataTypes.STRING,
      allowNull: false,
      defaultValue: "A"
    },
    dt_incl: {
      type: DataTypes.TIME,
      allowNull: false,
      defaultValue: sequelize.fn('now')
    },
    dt_ult_alt: {
      type: DataTypes.TIME,
      allowNull: false,
      defaultValue: sequelize.fn('now')
    }
  }, {
    tableName: 'apartamento'
  });
};

Apartamento Service: 公寓服务:

"use strict";
var model = require('../models');
var Utils = require('../utils/utils');

var service = {};
var Apartamento = model.apartamento;
var Bloco = model.bloco_condominio;
var Morador = model.morador;
var Pessoa = model.pessoa;

//Incluir relação OneToMany
Apartamento.hasMany(Morador, { as: "Moradores", foreignKey: 'id_apartamento' });
Morador.belongsTo(Apartamento, { foreignKey: 'id_apartamento' });

Morador.hasMany(Pessoa, { as: "Pessoa", foreignKey: 'id_pessoa' });
Pessoa.belongsTo(Morador, { foreignKey: 'id_pessoa' });

Bloco.hasMany(Apartamento, { as: "Bloco", foreignKey: 'id_bloco' });
Apartamento.hasMany(Bloco, { foreignKey: 'id_bloco' }); 

service.getApartamentoById = function(idApartamento) {
    return Apartamento.findById(idApartamento, {
            include: [
                { model: Morador, as: 'Moradores', include: [
                    { model: Pessoa, as: 'Pessoa'}
                ]},
                { model: Bloco, as: 'Bloco' }
            ]
        })
        .then(function(data) {
            return data;
        })
        .catch(function(err) {
            throw 'Erro ao consultar apartamento por ID: ' + err.message + ' - Request: '+JSON.stringify(idApartamento);
        });
};

I can perfectly retrieve the other hasMany associations, but still hasn't found a way to do so in the reverse way. 我可以完美地检索其他hasMany关联,但是仍然没有找到相反的方法。

Do you guys have any idea of how I should approach this issue in the correct manner? 你们对我应该如何正确解决此问题有任何想法吗?

Thanks in advance for your help! 在此先感谢您的帮助!

Best regards, Enrico Bergamo 最好的问候,恩里科·贝加莫

To make it simpler for me (only knowing English), I've grabbed the following from Google translate: 为了简化我的工作(只懂英语),我从Google翻译中抓取了以下内容:

Pessoa: Person
Morador: Dweller
Bloco: Block
Apartmento: Apartment

So, Dweller can have many People, an Apartment can have many Dwellers and a Block can have many Apartments. 因此,居民可以有很多人,一个公寓可以有很多居民,而一个街区可以有很多公寓。

Your definition on the other models indicates they're all 1:m, so I followed that assumption for Apartments and Blocks. 您在其他模型上的定义表明它们都是1:m,因此我对公寓和街区遵循了这一假设。

With that in mind, the following should work. 考虑到这一点,以下应该起作用。

Bloco.hasMany(Apartamento, { as: "Apartmento", foreignKey: 'id_bloco' });
Apartamento.belongsTo(Bloco, { foreignKey: 'id_bloco' }); 

Note: I've changed the as: "Bloco" to as: "Apartmento" and the second hasMany to belongsTo . 注意:我已经将as: "Bloco"更改as: "Apartmento" ,第二个hasMany属于belongsTo This might be where your issues were coming from. 这可能是您的问题所在。


Edit: The method to access the Apartments that belong to a Block is: 编辑:访问属于一个块的公寓的方法是:

bloco.getApartmento(options)

I have this working with this promise chain: 我有这个承诺链一起工作:

Bloco.create()
.then(block => {
  return Promise.all([
    block,
    Apartamento.bulkCreate([{
      id_bloco: block.id_bloco
    }, {
      id_bloco: block.id_bloco
    }, {
      id_bloco: block.id_bloco
    }, {
      id_bloco: block.id_bloco
    }, {}])
  ])
})
.spread((bloco, apartment) => {
  return bloco.getApartamento()
})
.then(apartments => {
  console.log(apartments.length); --> Logs 4 which matches the bulk create.
})

If I've misinterpreted, and it should be an n:m relationship (Apartments/Blocks), then you should use belongsToMany on each model and identify the through option. 如果我误解了,它应该是n:m的关系(公寓/街区),那么您应该在每个模型上使用belongsToMany并确定through选项。

Bloco.belongsToMany(Apartamento, { 
    as: "Apartmentos", 
    foreignKey: 'id_bloco', 
    through: "BlocoAparmento" 
});
Apartamento.belongsToMany(Bloco, { 
    as: "Blocos", 
    foreignKey: 'id_apartmento', 
    through: "BlocoAparmento" 
}); 

This will create an n:m joining table called "BlockApartmento". 这将创建一个称为“ BlockApartmento”的n:m连接表。 If you define that model, and use the model instead of the string, you'll have complete control over the models settings. 如果定义该模型,并使用模型而不是字符串,则可以完全控制模型设置。

This will give you the Bloco.getApartmentos( methods as well as opposite ( Apartmento.getBlocos( ) along with setAssociation , addAssoc... etc 这将为您提供Bloco.getApartmentos(方法以及相反的方法( Apartmento.getBlocos( )以及setAssociationaddAssoc...

http://docs.sequelizejs.com/manual/tutorial/associations.html#belongs-to-many-associations http://docs.sequelizejs.com/manual/tutorial/associations.html#belongs-to-many-associations

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM