sql - Knex 查询返回 bool 逻辑

标签 sql postgresql knex.js

我正在编写一些 knex 查询来检查提供的代码(也称为 voucher)在 4 个约束条件下是否合法。

  • 凭证存在
  • 凭证尚未过期
  • 优惠券适用于正确的事件
  • 还有足够的代金券

我当前的代码(尽管还没有完成)如下:

export default () => (async (req, res) => {
      const { eventId, orderId, voucher, left } = req.params;

      const [{ code }, { eventId }, { expiryDate }, {quantity}] = await Promise.all([
        knex('vouchers')
          .where({
            code: voucher
          })
          .first(),
        knex('vouchers')
          .where({
            event_id
          })
          .first(),
        knex('mv_vouchers')
        .where({
            voucher_id: code,
            // 'left', > , 0,

        })
          .first(),
      ]);
            if (code && eventId && expiryDate && quantity) {

              await knex.insert([{order_id: orderId}, {voucher_id: voucher}], 'id').into('order_vouchers');
              res.status(202).end();

            } else{
              res.status(404).end();
            }
      });

我担心的部分是分段代码。我看到有人在某个地方在线使用它,但我再也无法在 stackoverflow 上找到它了。在我的假设下,常量 codeeventId 等都应该返回 true 或 false,然后才能在我的 if 逻辑中使用。这是正确的还是完全错误的?

最佳答案

首先,codeeventId 应该只在该列的数据类型为 bool 时返回 bool。要获得 bool 值,您必须操纵每个查询的响应,例如通过检查响应中是否存在属性或将 case 语句添加到查询中(IMO 会变得有点困惑)。

其次,我建议不要使用与 Promise.All() 组合的 4 个查询,而是按照以下行移动到单个查询(假设您不需要明确知道查询没有结果的原因):

export default () => (async (req, res) => {
  const { eventId, voucher } = req.params;
  const response = await knex('vouchers')
    .join('mv_vouchers', 'vouchers.id', 'mv_vouchers.voucherId')
    .where('vouchers.code', '=', voucher)
    .where('vouchers.event_id', '=', eventId)
    .first()

关于sql - Knex 查询返回 bool 逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53083259/

相关文章:

database - DBUnit 坚持为未指定的值插入 null,但我希望使用 DB 默认值

node.js - 使用 knex-postgis 进行动态查询

sql - 查找所有重复的组,其中重复意味着包含相同成员的组

node.js - 在配置数据库时连接详细信息不可用 Digital Ocean

PHP收件箱系统

sql - 远程删除不一致地达到资源限制/超时

Java Hibernate 填充 transient 属性

SQL Server 类似 %% 的语句行为

Spring 数据锁定

postgresql - Postgres 动态 COPY 语句