最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to find or create with Knex? - Stack Overflow

programmeradmin0浏览0评论

In terms of a simple user registration, how can I do a find or create by username with best performance in mind? Guessing I need to use raw queries but I'm not so sql savvy as of yet.

Or at least some kind rejection if the username already exist.

In terms of a simple user registration, how can I do a find or create by username with best performance in mind? Guessing I need to use raw queries but I'm not so sql savvy as of yet.

Or at least some kind rejection if the username already exist.

Share Improve this question asked Aug 31, 2017 at 8:19 tribetribe 3212 silver badges10 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

With mysql you probably need like 3 queries, since it doesn't support well mon table expressions (maybe some really new mysql actually supports them) nor returning inserted data:

Get user, if not found insert, get user again (Mysql fetch the row just inserted).

Something like:

  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]}`));

I was dealing with this for a whole day. Not sure if this solution works with all databases supported by Knex. I'm using PostgreSQL.

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

评论列表(0)

  1. 暂无评论