findOrCreate 与包含

编程入门 行业动态 更新时间:2024-10-28 16:19:57
本文介绍了findOrCreate 与包含 - sequelize.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想创建一个锦标赛(如果不存在),以及一个与锦标赛关联的比赛(如果不存在).

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 与包含

本文发布于:2023-10-23 08:11:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1520280.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:findOrCreate

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!