javascript 方法链接 - knex.js

标签 javascript node.js knex.js

我是一名 PHP 开发人员,对于一个新项目,我决定使用 Node.js 后端。所以我对此还很陌生。

我正在使用 knex.js 来处理数据库连接并操作数据。 F.ex 我有以下查询:

let gastronomies = await knex
  .from('user')
  .innerJoin('profile', 'user.id', 'profile.user_id')
  .where('user.status', 1);

如果客户端将附加变量传递给函数,则应将其用作另一个查询参数

if(args.lat) {
    gastronomies = await knex
    .from('user')
    .innerJoin('profile', 'user.id', 'profile.user_id')
    .where('user.status', 1)
    .where('lat', 'like', args.lat); //there it is
  }

我想链接这些方法,但它根本不起作用。这就是我想到的:

let gastronomies = await knex
  .from('user')
  .select('*', {key: 'user.id'})
  .innerJoin('profile', 'user.id', 'profile.user_id')
  .where('user.status', 1);

if(args.lat)
    gastronomies.where('lat', 'like', args.lat);

但是它说美食没有一个叫做“where”的方法。有什么建议吗?

最佳答案

如果你想链接它,你应该使用async/await等待,因为它将触发对数据库的调用。 我会这样做:

const gastronomies = knex // no await here
  .from('user')
  .select('*', {key: 'user.id'})
  .innerJoin('profile', 'user.id', 'profile.user_id')
  .where('user.status', 1);

if(args.lat)
    gastronomies.where('lat', 'like', args.lat);

const response = await gastronomies;

您还可以在此处检查带有 promise 的问题的答案:Can I conditionally add a where() clause to my knex query?

关于javascript 方法链接 - knex.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50128043/

相关文章:

mysql - Bookshelf.js 使用 rand() 随机排序项目

javascript - 遍历这个结构?

javascript - CSS 中连字符和驼峰式大小写(font-size 和 fontSize)的使用区别

html - 矩形 customPOST 图像文件内容类型为 :multipart/form-data to NodeJS(Server)

javascript - js window.open 然后 print()

javascript - 在 Node.js 下存储 JSON 的简单方法

javascript - Mongoose 保存一对多

node.js - 无法在 postgres 插入中插入问号

javascript - 如何创建动态SectionList?

javascript - 如何使用 yyyymmdd 格式向日期添加 n 天但排除星期日?