如何使用 Knex 查找或创建?

How to find or create with Knex?

就简单的用户注册而言,如何根据用户名进行查找或创建才能获得最佳性能?我想我需要使用原始查询,但我还没有 sql 精明。

或者如果用户名已经存在,至少是某种拒绝。

使用 mysql 你可能需要 3 个查询,因为它不支持常见的 table 表达式(也许一些真正新的 mysql 实际上支持它们)也不返回插入的数据:

获取用户,如果找不到则插入,重新获取用户(Mysql fetch the row just inserted)。

类似于:

  knex.transaction(trx => {
    trx('users').where('username', name).then(res => {
      if (res.length === 0) {
        return trx('users').insert({ username: name }).then(() => {
          return trx('users').where('username', name);
        });
      } else {
        return res;
      }
    });
  }).then(res => console.log(`User is: ${res[0]}`));

我整天都在处理这个问题。不确定此解决方案是否适用于 Knex 支持的所有数据库。我正在使用 PostgreSQL。

knex('users')
  .insert(
    db('users')
      .select(knex.raw('? ? ?', [
        username,
        first_name,
        last_name
      ]))
      .whereNotExists(
        knex('users').select(0).where({username})
      )
      .limit(1)
  );