你好,我有一个关于 Sequelize 的问题
我有两个实体两个模型
用户
并匹配
一场比赛有两个用户
我怀疑我将如何建立这种关系
我要换两个user_id?
我的比赛基本上会有
比赛编号,球员编号一,球员编号二
我怀疑如何在 Sequelize 中对此进行关联或定义
最佳答案
您可以定义匹配如下。我假设你有 UserModel.id
作为 Seqeulize.INTEGER
。
const MatchModel = Sequelize.define("Match", {
// ... Other column declaration
// Two user column -- which are not linked yet.
playerOneId: {
type: Sequelize.INTEGER,
allowNull: false
},
playerTwoId: {
type: Sequelize.INTEGER,
allowNull: false
}
})
// Now time to link the UserModel
// I assume you have `UserModel` declared before doing this.
MatchModel.belongsTo(UserModel, {
foreignKey: {
name: "playerOneId"
},
as: "playerOne"
}
MatchModel.belongsTo(UserModel, {
foreignKey: {
name: "playerTwoId"
},
as: "playerTwo"
}
现在在查询
MatchModel
时执行以下操作MatchModel.findOne({
where: {
// Your condition goes here
},
includes: [
{
model: UserModel,
as: "playerOne"
},
{
model: UserModel,
as: "playerTwo"
},
]
})
关于node.js - 序列化同一类的两个关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59121509/