使用 knex.js 使用 select 查询的结果更新现有列
Using knex.js updates existing column with results of select query
产品(id、currentdraw、totaldraw、ratio)
产品是我的table
我想用currentdraw和totaldraw来更新比率
这是我的代码
Product.updateRatio = function(pid, cb) {
db('product')
.where({
productid : pid
})
.select('currentdraw', 'totaldraw')
.then(function(ratiolist) {
db('product')
.where({
productid : pid
})
.update({
ratio : ratiolist.currentdraw / ratiolist.totaldraw
})
cb(null, ratiolist);
})
.catch(function(err) {
cb(new GeneralErrors.Database());
console.log('updateRatio');
});
}
当我 运行 代码时,没有发生错误,但比率列没有更新。
不知道哪里错了
有人可以帮助我吗?谢谢
我想你的 ratiolist
是数组而不是对象,添加 console.dir(ratiolist)
以检查第一个查询返回的内容:
function(ratiolist) {
// here ratiolist is an array
db('product')
.where({
productid : pid
})
.update({
// undefined / undefined is NaN
ratio : ratiolist.currentdraw / ratiolist.totaldraw
})
// second query is not yet ran when this callback is called
// try to use promise chains...
cb(null, ratiolist);
})
执行此查询的更好方法是:
// return value passed as promise instead of callback
Product.updateRatio = function(pid) {
return db('product')
.where('productid', pid)
.update({
ratio : db.raw('?? / ??', ['currentdraw', 'totaldraw'])
})
.then(() => db('product').where('productid', pid));
}
如果您坚持使用回调,这应该有效:
Product.updateRatio = function(pid, cb) {
db('product')
.where('productid', pid)
.update({
ratio : db.raw('?? / ??', ['currentdraw', 'totaldraw'])
})
.then(() => db('product').where('productid', pid))
.then(ratiolist => cb(null, ratiolist));
}
产品(id、currentdraw、totaldraw、ratio)
产品是我的table
我想用currentdraw和totaldraw来更新比率
这是我的代码
Product.updateRatio = function(pid, cb) {
db('product')
.where({
productid : pid
})
.select('currentdraw', 'totaldraw')
.then(function(ratiolist) {
db('product')
.where({
productid : pid
})
.update({
ratio : ratiolist.currentdraw / ratiolist.totaldraw
})
cb(null, ratiolist);
})
.catch(function(err) {
cb(new GeneralErrors.Database());
console.log('updateRatio');
});
}
当我 运行 代码时,没有发生错误,但比率列没有更新。
不知道哪里错了
有人可以帮助我吗?谢谢
我想你的 ratiolist
是数组而不是对象,添加 console.dir(ratiolist)
以检查第一个查询返回的内容:
function(ratiolist) {
// here ratiolist is an array
db('product')
.where({
productid : pid
})
.update({
// undefined / undefined is NaN
ratio : ratiolist.currentdraw / ratiolist.totaldraw
})
// second query is not yet ran when this callback is called
// try to use promise chains...
cb(null, ratiolist);
})
执行此查询的更好方法是:
// return value passed as promise instead of callback
Product.updateRatio = function(pid) {
return db('product')
.where('productid', pid)
.update({
ratio : db.raw('?? / ??', ['currentdraw', 'totaldraw'])
})
.then(() => db('product').where('productid', pid));
}
如果您坚持使用回调,这应该有效:
Product.updateRatio = function(pid, cb) {
db('product')
.where('productid', pid)
.update({
ratio : db.raw('?? / ??', ['currentdraw', 'totaldraw'])
})
.then(() => db('product').where('productid', pid))
.then(ratiolist => cb(null, ratiolist));
}