我正在将 Sequelize 与 NodeJS 和 MySql 一起使用。 (最新版本)
我有一个用户模型 -
- 'id' 以及唯一键和主键。 “id”设置为自动递增。
- 一些用户详细信息,例如名字、姓氏、电子邮件等。
- 两个额外的唯一键(在 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/