如何使用Knex将唯一的数据插入到Postgres中?

问题描述:

我正在创建一个简单的“考勤”数据库,在这个数据库中,学生只能被允许每天“登记”一次。每个签入将包含一个user_id,名称,时间和日期。使用Knex,我怎么只允许每个学生每天签入一次。如何使用Knex将唯一的数据插入到Postgres中?

我试图从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 
     }); 
    } 
}); 
+0

谢谢!这工作,但我最终改变使用复合索引,所以它不会失败的任何竞争条件。像这样: table.unique(['user_id','check_date']); –