tri*_*ibe 3 javascript mysql node.js knex.js
就简单的用户注册而言,如何通过用户名进行查找或创建以实现最佳性能?猜测我需要使用原始查询,但到目前为止我还不太精通 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]}`));
Run Code Online (Sandbox Code Playgroud)