我想创建一个锦标赛(如果不存在),以及一个与锦标赛关联的比赛(如果不存在).
I want to create a Tournament (if not exists), and a Match (if not exists) associated to the Tournament.
let [match, created] = await Match.findOrCreate( { where: {scoreHome: 97, Tournament: {name: "USA South Men's Basketball"}}, include: [Tournament] })如果USA South Men's Basketball"锦标赛已经在数据库中(假设 ID 为 1),那么比赛应该使用 TournamentId: 1 创建.如果数据库中已经有一个带有 { 的比赛scoreHome: 97 and TournamentId: 1},则不应创建匹配项.
If the tournament 'USA South Men's Basketball' is already in the db (let's say with id 1), then the match should be created with TournamentId: 1. If there is already a match in the db with {scoreHome: 97 and TournamentId: 1}, then no match should be created.
let Match = sequelize.define('Match', { scoreHome: DataTypes.INTEGER, //... }) Match.associate = models => { Match.belongsTo(models.Tournament) }编辑这是错误:
[错误:无效值 [object Object]]
[Error: Invalid value [object Object]]
这很好用
let match = await Match.create({ scoreHome: 97, Tournament: {name: "USA South Men's Basketball"} },{include: [Tournament]} }) 推荐答案我不确定 sequelize 是否会允许这种深度 findOrCreate".但是您可以使用两个查询来达到想要的效果,并使用 sequelize 事务来确保两者链接在一起:
I am not sure sequelize will allow this "deep findOrCreate". But you can achieve the wanted effect using two queries, and the sequelize transaction to make sure the two are linked together:
const t = await sequelize.transaction(); try { const [tournament] = await Tournament.findOrCreate({ where: {name: "USA South Men's Basketball"}, { transaction: t } }) const [match] = await Match.findOrCreate({ where: {scoreHome: 97, tournamentId: tournament.id}, { transaction: t } }) tmit() } catch(err) { t.rollback() }它有点冗长,但是有了这个,你就可以确定你在做什么,而且(个人意见)对于在你之后的另一个开发者阅读来说也更具可读性.
It is a bit more verbose, but with this you are sure of what you do, and it is also (personal opinion) more readable for another dev reading that after you.
更多推荐
findOrCreate 与包含
发布评论