Sequelize - 如何 add/upsert 具有软删除行相同主键的行
Sequelize - How to add/upsert row with same primary key of soft deleted row
我正在使用 sequelize ORM。我有一个 table 的模型,我们通过 paranoid: true
.
启用了软删除
问题: 有没有办法做一个更新插入,如果对象已经存在于 table 但被软删除,它只会清除 deletedAt专栏?
示例设置:model.js
const Sequelize = require('sequelize')
const sequelize = new Sequelize(
dbName,
username,
password,
{
host,
dialect: 'mysql',
port
}
)
const model = sequelize.define(
'sample_table',
{
uid: {
type: Sequelize.STRING(60),
allowNull: false
primaryKey: true
},
deletedAt: {
type: Sequelize.Date,
allowNull: true,
default: null
}
},
{
tableName: 'sample_table'
deletedAt: true,
paranoid: true
}
)
示例用法:
const model = require('./model.js')
(async () => {
const myModel = await model.create({
uid: 'sample-uid'
})
await myModel.destroy()
// error is encountered because uid already exists
await model.create({
uid: 'sample-uid'
})
})()
是的,但您应该手动执行(例如,添加 catch 以创建方法并使用 .restore()
清除 deletedAt 列)。
或者您可以在 uid + deletedAt 上添加一个主键,您的代码应该可以正常运行。
const model = require('./model.js')
(async () => {
const myModel = await model.create({
uid: 'sample-uid'
})
await myModel.destroy()
// if primary key uid and deletedAt then no error here
await model.create({
uid: 'sample-uid'
})
})()
我正在使用 sequelize ORM。我有一个 table 的模型,我们通过 paranoid: true
.
问题: 有没有办法做一个更新插入,如果对象已经存在于 table 但被软删除,它只会清除 deletedAt专栏?
示例设置:model.js
const Sequelize = require('sequelize')
const sequelize = new Sequelize(
dbName,
username,
password,
{
host,
dialect: 'mysql',
port
}
)
const model = sequelize.define(
'sample_table',
{
uid: {
type: Sequelize.STRING(60),
allowNull: false
primaryKey: true
},
deletedAt: {
type: Sequelize.Date,
allowNull: true,
default: null
}
},
{
tableName: 'sample_table'
deletedAt: true,
paranoid: true
}
)
示例用法:
const model = require('./model.js')
(async () => {
const myModel = await model.create({
uid: 'sample-uid'
})
await myModel.destroy()
// error is encountered because uid already exists
await model.create({
uid: 'sample-uid'
})
})()
是的,但您应该手动执行(例如,添加 catch 以创建方法并使用 .restore()
清除 deletedAt 列)。
或者您可以在 uid + deletedAt 上添加一个主键,您的代码应该可以正常运行。
const model = require('./model.js')
(async () => {
const myModel = await model.create({
uid: 'sample-uid'
})
await myModel.destroy()
// if primary key uid and deletedAt then no error here
await model.create({
uid: 'sample-uid'
})
})()