knex 问题 whereNotExists

knex issue whereNotExists

我在使用 PostgreSQL 的 Knex 路由时遇到了一些问题。我正在尝试插入数据库,但仅当该项目不在数据库中时。我正在尝试使用不存在的地方,但它似乎没有按照我的意愿去做。我很感激你能给我的任何帮助。

谢谢!

app.post('/addcart', (req,res)=>{
  const{customer_id, product_id,item_quantity}=req.body;
  db('shopping_carts')
  .insert({
    customer_id:customer_id,
    product_id:product_id,
    item_quantity:item_quantity
  })
  .whereNotExists(db.select('*').from('shopping_carts').where('product_id',product_id))
  .then(item=>{
    console.log(item)
    res.json(item)
  })
  .catch((err)=>{
    if(err.column === 'customer_id'){
      res.status(400).json({message:err})
      console.log('test')
    }else{
      res.status(500).json({message:err})
      // console.log(err.name);
    }
  })
})

您不能将 whereNotExists 查询与插入查询结合使用,由于它的复杂性,它们不支持此操作(并且根据@mikael,大多数数据库不支持此操作)。因此 knex 忽略了 whereNotExists 在方法链中插入后的调用。

您需要先检查是否存在,然后通过单独的调用进行插入。

您也可以编写原始查询。这是一个例子,它并不漂亮: https://github.com/tgriesser/knex/commit/e74f43cfe57ab27b02250948f8706d16c5d821b8

但是,当您尝试这样做时,您将 运行 陷入 concurrency/lock 问题。您最好使用唯一键并让数据库拒绝插入。然后就可以抓了:

.catch((err) => {
  if (err.code === 23505) { res.status(500).json({message: 'duplicate'});
}

编辑,如果您有兴趣,请提供更多信息。这里有一个关于这个话题的很长的话题: https://github.com/tgriesser/knex/issues/871

编辑:来自@mikael 的关于数据库和 insert-where 的帖子: https://github.com/tgriesser/knex/issues/871