Knex error: missing FROM-clause entry for table

Knex error: missing FROM-clause entry for table

我在关系数据库中使用 Knex.js。目前正在尝试做一个相对简单的连接,不涉及别名。

knex('tools_users')
  .select('*').from('tools_users')
  .innerJoin('users', 'users.id', 'tools_users.user_id')
  .innerJoin('tools', 'tools.id', 'tools_users.tool_id')
  .where('users.id', userId)
  .andWhere('tools.id', toolId)
  .andWhere('tools_users.current_durability', '>', 0)
  .first()
  .decrement('tools_users.current_durability', durabilityUsed)
  .then(() => {
    console.log('tool updated');
  })
  .catch((err) => {
    console.error(err);
  });

console.error(err) 产生了这个错误:error: missing FROM-clause entry for table "users"

我在网上其他地方找到的每个解决方案都表明这是一个别名问题。不过我没有使用任何别名。不知道还有什么可做的。 我发现 github 回购中的 knex 问题尚无定论。

Knex 不支持连接更新查询的数据,因此您必须进行两个单独的查询...像这样的东西(我没有测试查询,所以可能有拼写错误):

knex('tools_users')
  .innerJoin('users', 'users.id', 'tools_users.user_id')
  .innerJoin('tools', 'tools.id', 'tools_users.tool_id')
  .where('users.id', userId)
  .andWhere('tools.id', toolId)
  .andWhere('tools_users.current_durability', '>', 0)
  .first()
  .then((tool_user) => {
    return knex('tool_user').where('id', tool_user.id)
      .decrement('current_durability', durabilityUsed);
  })
  .then(() => {
    console.log('tool updated');
  })
  .catch((err) => {
    console.error(err);
  });

或带有子查询的单个查询

knex('tools_users')
  .decrement('current_durability', durabilityUsed)
  .whereIn('id', (subQueryBuilder) => {
    subQueryBuilder
      .from('tools_users')
      .select('id')
      .innerJoin('users', 'users.id', 'tools_users.user_id')
      .innerJoin('tools', 'tools.id', 'tools_users.tool_id')
      .where('users.id', userId)
      .andWhere('tools.id', toolId)
      .andWhere('tools_users.current_durability', '>', 0)
      .limit(1);
  })
  .then(() => {
    console.log('tool updated');
  })
  .catch((err) => {
    console.error(err);
  });