【问题标题】:how to use 'and' within the 'on' condition of 'join' in knex.js如何在 knex.js 中的“join”的“on”条件下使用“and”
【发布时间】:2020-10-24 07:53:54
【问题描述】:

我想在 knex.js 中实现下面的 sql 代码:

select c.id,c.parent_id,c.comment,u.username,c.postid from comments as
     c join post_details as p on (p.id = c.postid and c.postid=15)join
     users as u on (u.id = c.userid);

我尝试过这样做:

db('comments AS c')
  .join('post_details AS p', function () {
    this.on('p.id', '=', 'c.postid').on('c.postid', '=', db.raw('?', [postid]));
  })
  .join('users AS u', 'u.id', '=', 'c.userid')
  .select(['c.id', 'c.parent_id', 'c.comment', 'u.username', 'c.postid', 'c.userid'])
  .then((data) => {
    console.log(data);
    res.json(data);
  })
  .catch((err) => res.status(400).json('unable to fetch'));

但我在调用 URL 时无法获取。

所以请帮忙。提前致谢。

【问题讨论】:

  • 您得到的确切错误是什么?
  • @felixmosh 我收到输入语法无效的错误

标签: javascript sql json express knex.js


【解决方案1】:

试试这个:

db('comments AS c')
  .join('post_details AS p', (joinBuilder) => {
    return joinBuilder.on('p.id', '=', 'c.postid').andOn('c.postid', '=', db.raw('?', [postid]));
  })
  .join('users AS u', 'u.id', '=', 'c.userid')
  .select(['c.id', 'c.parent_id', 'c.comment', 'u.username', 'c.postid', 'c.userid'])
  .then((data) => {
    console.log(data);
    res.json(data);
  })
  .catch((err) => res.status(400).json('unable to fetch'));

【讨论】:

    猜你喜欢
    • 2013-05-04
    • 2023-03-05
    • 2021-01-15
    • 1970-01-01
    • 2016-02-16
    • 1970-01-01
    • 2013-09-23
    • 2016-12-26
    • 2019-02-16
    相关资源
    最近更新 更多