mysql - knex 使用 Promise 同步两个 mysql 查询

标签 mysql node.js express promise knex.js

Promise.all(sendData.franchisee.map(row => {

    return  knex('designer.settings').select('value').where({setting_key : 'PRICING_TIER'})
            .then(pricing_tier => {

                row.pricing_tier = pricing_tier[0].value;

                knex('designer.pricing_tier').select('tier_title').where({id : row.pricing_tier})
                .then(tier_title =>{

                    row.tier_title = tier_title[0].tier_title;
                    return row;
                })

            });

})).then(response => {
    cb(sendData);     
});

听到 promise “designer.settings”和“designer.pricing_tier”中的两个查询。 当执行“designer.settings”时,我在执行“designer.pricing_tier”后在行中得到了该结果,但该输出未在行中。 row.tier_title = tier_title[0].tier_title 不在最终的 sendData 中。 如何在一个 promise 中同步两个查询?

最佳答案

不确定查询是否实际上执行完全相同的操作,但这只是演示了如何使用 knex 正确执行上述查询的基本思想。

与加入定价层以防止需要 2 个单独的查询实际上是一样的。

Promise.all(
  sendData.franchisee.map(row => {
    return knex('pricing_tier') 
      .withSchema('designer') // <-- selecting schema correctly in knex
      // this join could have been done as a subquery in select too...
      .join('settings', 'settings.setting_key', knex.raw('?', ['PRICING_TIER'])) 
      .select('settings.value', 'pricing_tier.tier_title')
      .where('pricing_tier.id', row.pricing_tier)
      .then(rows => {
        row.pricing_tier = rows[0].value;
        row.tier_title = rows[0].tier_title;
        return row;
      });
  })
).then(response => {
  cb(sendData); // <--- generally bad idea to mix promises and callbacks
});

生成的 SQL 是这样的:

select 
  `settings`.`value`, 
  `pricing_tier`.`tier_title` 
from `designer`.`pricing_tier` 
inner join `designer`.`settings` on `settings`.`setting_key` = 'PRICING_TIER' 
where `pricing_tier`.`id` = 3219

关于mysql - knex 使用 Promise 同步两个 mysql 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46951993/

相关文章:

mysql - 不存在 - SQL 查询

PHP + MySQL 问题 - 我哪里出错了?

mysql - BASH:SSH 进入服务器,查询 MYSQL 有趣的东西

node.js - 如何在 Bot Framework Node.js 网络聊天中隐藏直接 secret 并传递 token

javascript - 普通对象 Mongoose 不适用于排序

mysql - 无法通过tomcat连接远程mysql

node.js - 如何使用 ExpressJS 一次 API 调用下载多个文件

node.js - 两个独立的 Heroku(Node 后端和 React 前端)之间的通信?

node.js - 如果我导入没有 `ERR_MODULE_NOT_FOUND` 扩展名的文件,ExpressJs 将返回错误 `js`

javascript - 从 node.js 解析 HTML 时如何确定 URL