我是一名 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/