续集属于多

alp*_*ogg 3 many-to-many associations sequelize.js

我使用了 Sequelize 并使用belongsToMany(). 但是,当我查询数据时,如下所示:

api.models.operator.find({ 
      where: { id: connection.params.id }, 
      include: [ 
        { model: api.models.permission, 
          include: [
            { model: api.models.activity }
          ]
        } 
      ]
    })
Run Code Online (Sandbox Code Playgroud)

我收到一个activity is not associated to permission!错误。为什么?是不是belongsToMany 通过Permission to Operator 连接Activity 意味着关联?

我的权限模型:

module.exports = function(sequelize, DataTypes) {

  return sequelize.define("permission", 
    {
      id: {
        type: DataTypes.BIGINT,
        allowNull: false,
        primaryKey: true,
        autoIncrement: true
      },
      operator_id: {
        type: DataTypes.BIGINT,
        allowNull: false,
        references: 'operator',
        referencesKey: 'id',
        comment: "The Operator in this Permission."
      },
      activity_id: {
        type: DataTypes.BIGINT,
        allowNull: false,
        references: 'activity',
        referencesKey: 'id',
        comment: "The Activity in this Permission."
      },
      createdAt: {
        type: DataTypes.DATE,
        allowNull: false,
        defaultValue: DataTypes.NOW,
        comment: "Date of record creation."
      },
      updatedAt: {
        type: DataTypes.DATE,
        allowNull: false,
        defaultValue: DataTypes.NOW,
        comment: "Date of last record update."
      },
      deletedAt: {
        type: DataTypes.DATE,
        comment: "Date record was marked as deleted."
      }
    }, 
    {
      comment: "A Permission indicates an allowed Activity by an Operator, ex: superadmin is allowed to 'POST /workorders'.",
      classMethods: {
        associate: function(models) {

          models.operator.belongsToMany(models.activity, {through: models.permission, foreignKey: 'operator_id', onDelete: 'CASCADE', onUpdate: 'CASCADE'});
          models.activity.belongsToMany(models.operator, {through: models.permission, foreignKey: 'activity_id', onDelete: 'CASCADE', onUpdate: 'CASCADE'});

        }
      }
    }
  );

}
Run Code Online (Sandbox Code Playgroud)

小智 5

我自己解决如下:

ModelA.belongsToMany(ModelB, {
        through: 'ModelC',
        foreignKey: 'ModelAID'
    });
Run Code Online (Sandbox Code Playgroud)

你只需要打电话:

ModelA.findAll({
include: [{
    model: ModelB
}]}).then(function(success) {}, function(error) {});
Run Code Online (Sandbox Code Playgroud)

如果你想使用:

ModelB.findAll({
include: [{
    model: ModelA
}]}).then(function(success) {}, function(error) {});
Run Code Online (Sandbox Code Playgroud)

你必须声明

ModelB.belongsToMany(ModelA, {
        through: 'ModelC',
        foreignKey: 'ModelBID'
    });
Run Code Online (Sandbox Code Playgroud)

^^ 祝你好运!!!!^^。