首先,我对 Node.JS 相当陌生,对 Sequelize 甚至更陌生,这已经困扰我一段时间了。我有以下模型实体:
Match.js
module.exports = function(sequelize, DataTypes) {
var Match = sequelize.define('Match', {
matchId: {
type: DataTypes.BIGINT,
field: 'match_id'
},
server: {
type: DataTypes.STRING
},
(...)
rankedBoo: {
type: DataTypes.BOOLEAN,
field: 'ranked_boo'
}
}, {
classMethods: {
associate: function(models) {
Match.belongsToMany(models.Summoner, {as: 'Participants', through: 'SummonerMatch'});
}
},
freezeTableName: true,
underscored: true
});
return Match;
};
召唤师.js
module.exports = function(sequelize, DataTypes) {
var Summoner = sequelize.define('Summoner', {
summonerId: {
type: DataTypes.INTEGER,
field: 'summoner_id'
},
server: {
type: DataTypes.STRING
},
summonerName: {
type: DataTypes.STRING,
field: 'summoner_name'
},
mainChampion: {
type: DataTypes.INTEGER,
field: 'main_champion'
}
}, {
classMethods: {
associate: function(models) {
Summoner.belongsToMany(models.Match, {as: 'SummonerMatches', through: 'SummonerMatch'});
Summoner.hasOne(models.RankedStats);
Summoner.hasMany(models.RankedHistory, { as: { singular: 'RankedHistory', plural: 'RankedHistory' }});
}
},
freezeTableName: true,
underscored: true
});
return Summoner;
};
SummonerMatch.js
module.exports = function(sequelize, DataTypes) {
var SummonerMatch = sequelize.define('SummonerMatch', {
championId: {
type: DataTypes.INTEGER,
field: 'champion_id'
},
role: {
type: DataTypes.STRING
},
(...)
sightWardsBought: {
type: DataTypes.INTEGER,
field: 'sight_wards_bought'
}
}, {
freezeTableName: true,
underscored: true
});
return SummonerMatch;
};
现在我正在尝试创建一个新的匹配,并将其与召唤师关联起来,我正在执行以下操作:
summoner.createSummonerMatch(matchInfo, matchDetails).then(
function () {
callback();
return null;
});
Where 比赛信息包含“Match”实体的属性,以及比赛详情包含“SummonerMatch”实体的属性。
这很好,但它不会检查匹配是否已经存在,所以我尝试使用查找或创建 here.
models.Match.findOrCreate({
include: [ {model: models.Summoner, as: 'Participants'}],
where: { matchId: matchInfo.matchId, server: matchInfo.server },
defaults: {
matchMode: queueType,
matchDate: new Date(matchCreation),
matchDuration: matchDurationInSeconds,
rankedBoo: rankedBoo
}
}).spread(function(match, created) {
console.log(created)
});
这几乎成功了(在 Match 表中创建一个新行,但不在 SummonerMatch 中创建)。我该如何将信息插入 SummonerMatch 中?尝试了一些事情(向默认值添加属性、将其切换到数组、使用包含进行调整,但到目前为止没有成功。
我可能错过了一些东西,但我不知道是什么。任何帮助深表感谢 :)
[编辑] 如果有人来这里寻找如何做到这一点的答案,这可行,但我不确定这是否是最好的方法:
models.Match.findOrCreate({
include: [ {model: models.Summoner, as: 'Participants'}],
where: { matchId: matchInfo.matchId, server: matchInfo.server },
defaults: {
matchMode: queueType,
matchDate: new Date(matchCreation),
matchDuration: matchDurationInSeconds,
rankedBoo: rankedBoo
}
}).spread(function(match, created) {
match.addParticipant(summoner, matchDetails).then(
function () {
console.log('Done')
}
)
});
如果匹配不存在,它将创建一个匹配,然后添加一个参与者。难道就没有办法一次完成这一切吗?