我正在尝试连接两个表,一个计划表和一个计划详细信息表。下面是两个表格的外观示例。
计划表

+---------+------+-----------+
| user_id | plan | is_active |
+---------+------+-----------+
|  1      |  10  |    true   |
|  1      |  11  |   false   |
|  2      |  11  |    true   |

平面图明细表
+---------+------+-------+-----------+
| plan_id | cost | price | is_active |
+---------+------+-------+-----------+
|  10     |  19  |  199  |    true   |
|  11     |  13  |  149  |    true   |

我只想拉现行计划成本和价格相关的每个用户现在,我的knex声明是:
knex('plans')
  .where({
    user_id: 1,
    is_active: 'true'
  })
  .select(
    'plans.plan',
    'plan_details.cost',
    'plan_details.price'
  )
  .join('plan_details as plan_details', 'plan_details.plan_id', 'plans.plan')
  .then(function (user_plan_id) {
    console.log(user_plan_id);
  });

如果我把is_active: 'true'放在里面,我会得到一个Unhandled rejection error: column reference "is_active" is ambiguous。如果我去掉is_active部分,那么我会得到两个计划的信息,它们都引用了用户,即使我只想知道哪些计划对用户是活动的。
如何仅获取用户的活动计划?我使用KNEX.JS作为ORM,但我也很高兴使用原始SQL。

最佳答案

使用knex时,应该:

knex('plans')
  .select(
    'plans.plan',
    'plan_details.cost',
    'plan_details.price'
  )
  .join('plan_details as plan_details', 'plan_details.plan_id', 'plans.plan')
  .where('plan.user_id', 1)
  .where('plan.is_active', true)
  .then(function (user_plan_id) {
    console.log(user_plan_id);
  });

10-04 23:42
查看更多