Sequelize.js:获取多对多结点模型的关联

时间:2018-11-18 17:31:20

标签: javascript orm sequelize.js

我有一些申请。有一个角色,可以属于多个组。一个小组可以有很多角色,也有很多等级。每个角色都有指定的等级。各个组的排名不同。

字符模型:

module.exports = (sequelize, DataTypes) => {
  let Character = sequelize.define('Character', {
   /* attributes */
  }, {});
  Character.associate = (models) => {
    Character.hasMany(models.outfit, { foreignKey: 'owner' });
    Character.belongsToMany(models.group, { through: models.groupmember });
  };

  return Character;
};

组模型:

module.exports = (sequelize, DataTypes) => {
  let Group = sequelize.define('Group', {
    /* attributes */
  }, {});
  Group.associate = function (models) {
    Group.belongsToMany(models.character, { through: models.groupmember, as: 'members' });
    Group.hasMany(models.grouprank);
  };
  return Group;
};

GroupMember(连接表)模型:

module.exports = (sequelize, DataTypes) => {
  let GroupMember = sequelize.define('GroupMember', {
/* groupId, characterId are generated by sequelize */
    rankId: DataTypes.INTEGER
  }, {});
  GroupMember.associate = function (models) {
    GroupMember.belongsTo(models.grouprank, { foreignKey: 'rankId', targetKey: 'id' });
  };
  return GroupMember;
};

小组排名模型:(我的问题无关紧要)

  module.exports = (sequelize, DataTypes) => {
      let GroupRank = sequelize.define('GroupRank', {
// atributes
      }, {});
      GroupRank.associate = function (models) {
        GroupRank.belongsTo(models.group);
        GroupRank.hasMany(models.groupmember, { foreignKey: 'rankId' });
      };
      return GroupRank;
    };

我在联结表中添加了rankId列,但在检索包含所有字符组以及其排名的Character时遇到问题。 我当前的代码,该代码返回角色,他所属的组并进行排名,但是ALL属于该组。我只需要rankId指定的ID等级。

database.character.findById(characterId, {
    include: [{
      model: database.group,
      through: database.groupmember,
      include: {
        model: database.grouprank,
       /* where: { id: '$GroupMember.rankId$' } */
      }
    }]
  }).then(result => {
  });

是的。我知道它看起来很奇怪,它缺少CamelCase,但是我的问题是其他问题。我尝试使用where属性进行查询,但是Sequelize正在解析字符串,因此无法在其中放置列名。我希望这个问题足够稳定。谢谢您的时间!

1 个答案:

答案 0 :(得分:0)

我认为下面的代码终于对我有用。 http://docs.sequelizejs.com/class/lib/sequelize.js~Sequelize.html#static-method-literal

 database.character.findById(characterId, {
    include: [{
      model: database.group,
      through: database.groupmember,
      include: {
        model: database.grouprank,
        where: database.Sequelize.literal('`Groups->GroupRanks`.`id` = `Groups->GroupMember`.`rankId`')
      }
    }]
  })

编辑:最后,我决定按照此处所述重写模型-> FindAll with includes involving a complicated many-to-(many-to-many) relationship (sequelizejs)