在belongsToMany关联的“through”表上查找 – 查找或创build

首先,我对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; }; 

Summoner.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; }; 

现在我正在尝试创build一个新的匹配,并将其与召唤者相关联,并且我正在执行以下操作:

 summoner.createSummonerMatch(matchInfo, matchDetails).then( function () { callback(); return null; }); 

其中matchInfo包含“Match”实体的属性, matchDetails包含“SummonerMatch”实体的属性。

这很好,所有,但它不检查匹配是否已经存在,所以我试图在这里使用findOrCreate

 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表中创build一个新行,但不是在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') } ) }); 

如果它不存在,则创build一个匹配,然后添加一个参与者。 没有办法一次完成这一切吗?