sequelize 中 findOrCreate() 和 upsert() 的区别
Difference between findOrCreate() and upsert() in sequelize
我正在阅读 over the doc,其中提到了两种执行更新插入的方法:findOrCreate()
或 upsert()
。我阅读了描述,但我仍然不清楚有什么区别。
upsert()
接着说:
Note that the unique index must be defined in your sequelize model and not just in the table. Otherwise you may experience a unique constraint violation, because sequelize fails to identify the row that should be updated.
这是否意味着 upsert()
明确要求我在模型中定义一个 id
UNIQUE 主字段?即:
var Something = sequelize.define("Something", { id: {
type: DataTypes.INTEGER,
primaryKey: true,
unique: true,
allowNull: false}});
如果是这样,为什么 findOrCreate()
没有那个限制?
有人可以解释什么时候应该使用 findOrCreate()
和 upsert()
的用例,以及为什么 upsert()
有唯一约束要求而 findOrCreate()
似乎没有需要它吗?
.findOrCreate
将使用您提供的参数查询数据库,如果没有匹配项,它将使用相同的参数执行插入操作。而 .upsert
的要点是更新或插入记录。在更新操作的情况下,逻辑要求您根据唯一键查找记录,并且只有在找到此唯一记录后,才根据提供的参数更新其值。如果您找不到唯一的记录,那么您只能执行插入。
我希望这是有道理的。
主要区别在于 Id 字段。在更新插入的情况下,您需要 id 字段。但有时,您不使用 id 字段。例如,当从外部提供者字段创建用户时,比如 fb,如果用户记录的 ID 已经存在,您将不会有它。在这种情况下,您将必须在 fb 返回的字段之一上使用 findOrCreate,例如电子邮件。 findOrCreate user 其中email是fb返回的email
我正在阅读 over the doc,其中提到了两种执行更新插入的方法:findOrCreate()
或 upsert()
。我阅读了描述,但我仍然不清楚有什么区别。
upsert()
接着说:
Note that the unique index must be defined in your sequelize model and not just in the table. Otherwise you may experience a unique constraint violation, because sequelize fails to identify the row that should be updated.
这是否意味着 upsert()
明确要求我在模型中定义一个 id
UNIQUE 主字段?即:
var Something = sequelize.define("Something", { id: {
type: DataTypes.INTEGER,
primaryKey: true,
unique: true,
allowNull: false}});
如果是这样,为什么 findOrCreate()
没有那个限制?
有人可以解释什么时候应该使用 findOrCreate()
和 upsert()
的用例,以及为什么 upsert()
有唯一约束要求而 findOrCreate()
似乎没有需要它吗?
.findOrCreate
将使用您提供的参数查询数据库,如果没有匹配项,它将使用相同的参数执行插入操作。而 .upsert
的要点是更新或插入记录。在更新操作的情况下,逻辑要求您根据唯一键查找记录,并且只有在找到此唯一记录后,才根据提供的参数更新其值。如果您找不到唯一的记录,那么您只能执行插入。
我希望这是有道理的。
主要区别在于 Id 字段。在更新插入的情况下,您需要 id 字段。但有时,您不使用 id 字段。例如,当从外部提供者字段创建用户时,比如 fb,如果用户记录的 ID 已经存在,您将不会有它。在这种情况下,您将必须在 fb 返回的字段之一上使用 findOrCreate,例如电子邮件。 findOrCreate user 其中email是fb返回的email