我正在创建一个简单的“出勤”数据库,学生每天只能“签到”一次。每次 checkin 都将包含用户 ID、姓名、时间和日期。使用 Knex,我怎么能只允许每个学生每天签到一次。
我尝试了来自 this thread 的“whereNotExists”的几种变体但似乎没有任何效果。
目前这是我的插入语句:
db('checkins').insert(db
.select(attrs.user_id, attrs.user_name, attrs.date, attrs.created_at)
.whereNotExists(db('checkins').where('user_name', attrs.user_name).andWhere('date', attrs.date).then(() => {
console.log('successful insert')
}))
然后我收到此错误(“alice_id”是我在“attrs.user_id”中使用的测试值):
Unhandled rejection error: column "alice_id" does not exist
最佳答案
你应该在插入之前验证,即
db('checkins')
.where({
user_id: attrs.user_id,
date: attrs.date
})
.first() // getting the first value
.then((found) => {
if (found){
res.json('already present');
}else{
// now insert data
db('checkins')
.insert({
// your data
});
}
});
关于javascript - 如何使用 Knex 仅将唯一数据插入 Postgres?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43443858/