mysql - Sequelize findOrCreate 在具有附加唯一键的模型上返回 SequelizeUniqueContraintError

标签 mysql node.js sequelize.js

我正在将 Sequelize 与 NodeJS 和 MySql 一起使用。 (最新版本)

我有一个用户模型 -

  1. 'id' 以及唯一键和主键。 “id”设置为自动递增。
  2. 一些用户详细信息,例如名字、姓氏、电子邮件等。
  3. 两个额外的唯一键(在 Sequelize 模型和数据库中标记为唯一)-“用户名”和“电子邮件”

我正在使用“findOrCreate”方法来创建或查找。如果记录不存在,我的代码会创建一条记录,但当我尝试查找此记录时,会在“用户名”字段上抛出 UniqueConstraintError (ER_DUP_ENTRY) --> SequelizeUniqueContraintError 。基本上,findOrCreate 尝试第二次创建记录而不是查找它。

I was able to fix this issue by manually doing a find and if not found then create. But I need the flag returned by the 'findOrCreate' method which helps determine whether a record was created or found.

有人可以帮忙吗?

最佳答案

我能够通过在“where”子句中将唯一键传递给模型的“findOrCreate”方法并在“defaults”子句中设置所有其他表属性的值来解决此问题。

对于例如。 - Employee.findOrCreate({where: {employeeId: 'ABCD1234'}, defaults: {role: 'Analyst'}});

Where employeeId is a Unique Key. (I assume that the primary key 'id' field is set to Auto Increment)

请引用官方教程中提供的示例。 here

关于mysql - Sequelize findOrCreate 在具有附加唯一键的模型上返回 SequelizeUniqueContraintError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47455126/

相关文章:

mysql 内连接

php - MySQL+Php服务器最多能有多少个并发连接?

mysql - 按重复顺序排序,顶部优先,有限制

javascript - 无法读取二维数组的 for 循环中未定义的属性 'length'

javascript - Node.js:由于 URL 编码的 GET 参数而导致外部资源的路径困惑?

node.js - NGINX:将所有请求重定向到我的本地主机端口到 https/SSL

mysql - 一对多sequelizejs ORM未能得到结果

node.js - 在 ubuntu 18.04 上拒绝与 postgres 的 Sequelize 连接

node.js - 为什么我们需要 Sequelize 'seed' ?

php - MySQL从结果表中显示球队排名