Sar*_*ala 6 associations node.js sequelize.js
我正在尝试使用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'
});
};
Run Code Online (Sandbox Code Playgroud)
资源模式:
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'
});
};
Run Code Online (Sandbox Code Playgroud)
协会:
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'
});
Run Code Online (Sandbox Code Playgroud)
虽然我在关联时提到了 targetKey,但它在连接表时采用的是 PrimaryKey。
执行。
Note.findAll({
include: [{
model: Resource,
as: 'Note_Updated_By'
}],
where: {
Status: {
[SQLOP.or]: ['Active', 'ACTIVE']
}
}
}).then(function (response) {
callback(response);
});
Run Code Online (Sandbox Code Playgroud)
在执行的基础上,生成此选择查询。
SELECT * FROM `note` LEFT OUTER JOIN `resource` AS `Note_Updated_By` ON `note`.`NoteID` = `Note_Updated_By`.`ResourceID`;
Run Code Online (Sandbox Code Playgroud)
代替note。NoteID, 它应该是note。UpdatedBy
val*_*lis 11
从新版本开始,我使用"sequelize": "^5.8.12"
usesourceKey而不是targetKeyfor hasOne,并且hasMany关系对我有用。
ModelName.hasOne(ModelName1, {
as: 'SomeAlias',
foreignKey: 'foreign_key',
onDelete: 'NO ACTION',
onUpdate: 'NO ACTION',
sourceKey: 'YOUR_CUSTOM_ASSOCIATION_KEY'
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5510 次 |
| 最近记录: |