Sequelize targetKey不工作

问题描述 投票:1回答:1

我试图使用sequelize关联两个模型“注意”和“资源”。但是,targetKey未按预期工作。

注意模态:

module.exports = function(sequelize, DataTypes) {
  return sequelize.define('note', {
    NoteID: {
      type: DataTypes.INTEGER(11),
      allowNull: false,
      primaryKey: true,
      autoIncrement: true
    },
    Title: {
      type: DataTypes.STRING(50),
      allowNull: true
    },
    Note: {
      type: DataTypes.STRING(500),
      allowNull: false
    },
    CreatedBy: {
      type: DataTypes.INTEGER(11),
      allowNull: false,
      references: {
        model: 'resource',
        key: 'ResourceID'
      }
    },
    UpdatedBy: {
      type: DataTypes.INTEGER(11),
      allowNull: true,
      references: {
        model: 'resource',
        key: 'ResourceID'
      }
    }
  }, {
    tableName: 'note'
  });
};

资源模式:

module.exports = function(sequelize, DataTypes) {
  return sequelize.define('resource', {
    ResourceID: {
      type: DataTypes.INTEGER(11),
      allowNull: false,
      primaryKey: true,
      autoIncrement: true
    },
    FirstName: {
      type: DataTypes.STRING(250),
      allowNull: false
    },
    LastName: {
      type: DataTypes.STRING(250),
      allowNull: false
    }
  }, {
    tableName: 'resource'
  });
};

协会:

Resource.belongsTo(Note,{
    foreignKey: 'UpdatedBy',
    as: 'Resource_Updated_Note'
});

Note.hasOne(Resource,{
    foreignKey: 'ResourceID',
    targetKey: 'UpdatedBy',
    as: 'Note_Updated_By'
});

Resource.belongsTo(Note,{
    foreignKey: 'CreatedBy',
    as: 'Resource_Created_Note'
});

Note.hasOne(Resource,{
    foreignKey: 'ResourceID',
    targetKey: 'CreatedBy',
    as: 'Note_Created_By'
});

虽然我在关联时提到了targetKey,但是在加入表时它正在使用PrimaryKey。

执行。

Note.findAll({
        include: [{
            model: Resource,
            as: 'Note_Updated_By'
        }],
        where: {
            Status: {
                [SQLOP.or]: ['Active', 'ACTIVE']
            }
        }
    }).then(function (response) {
        callback(response);
    });

在执行的基础上,生成该选择查询。

SELECT * FROM `note` LEFT OUTER JOIN `resource` AS `Note_Updated_By` ON `note`.`NoteID` = `Note_Updated_By`.`ResourceID`;

而不是note.NoteID,它应该是note.UpdatedBy

node.js associations sequelize.js
1个回答
0
投票

对于未来的游客,从2018年8月开始,这仍然是一个带有续集的known issue

© www.soinside.com 2019 - 2024. All rights reserved.