就简单的用户注册而言,我该如何考虑到最佳性能来通过用户名进行查找或创建?猜猜我需要使用原始查询,但到目前为止我还不太懂sql。
或至少某种拒绝(如果用户名已经存在)。
使用mysql时,您可能需要3个查询,因为它不支持常见的表表达式(也许某些真正的新mysql实际上支持它们),也不返回插入的数据:
获取用户,如果找不到,请再次获取用户(Mysql获取刚刚插入的行)。
就像是:
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]}`));
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句