admin管理员组文章数量:1335887
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 badges2 Answers
Reset to default 5With 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)
);
本文标签: javascriptHow to find or create with KnexStack Overflow
版权声明:本文标题:javascript - How to find or create with Knex? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742397304a2467186.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论