findOrCreate()和upsert()之间的区别
我正在阅读文档 ,它提到了两种做upsert的方法: 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()
时候的用例,以及当findOrCreate()
似乎不需要时,为什么upsert()
有唯一的约束条件?
.findOrCreate
将使用您提供的参数查询数据库,如果不匹配,将使用相同的参数执行插入操作。 而.upsert
的要点是更新或插入logging。 在更新操作的情况下,逻辑规定您查找基于唯一键的logging,只有当您find此唯一logging时,才根据提供的参数更新其值。 如果您无法find唯一logging,只有这样才能执行插入操作。
我希望这是有道理的。