我正在尝试使用sequelize关联两个模型“Note”和“Resource”。但是,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