【发布时间】:2019-06-03 06:44:42
【问题描述】:
我有一个 SQL 查询 (Postgres),其中包含多个 joins,我无法将其转换为单个 Knex.js 语句。这是 SQL 查询:
SELECT
User.id, User.name, User.email,
Role.name AS r_name,
UserPofile.id AS p_id, UserPofile.date_of_birth AS p_dob,
AuthToken.id AS at_id, AuthToken.token AS at_token, AuthToken.platform AS at_platform
FROM public."user" User
LEFT JOIN public."user_role" UserRole ON User.id = UserRole.user_id
LEFT JOIN public."role" Role ON UserRole.role_id = Role.id
LEFT JOIN public."application" Application ON UserProfile.app_id = Application.id
LEFT JOIN public."user_profile" UserProfile ON User.id = UserProfile.user_id
LEFT JOIN public."auth_token" AuthToken ON User.id = AuthToken.user_id
WHERE
User.email LIKE 'some@email.com' AND
Application.name LIKE 'awesome-application' AND
AuthToken.platform LIKE 'mobile';
这是我的 Knex.js 代码:
return knex('user').where({ email:'some@email.com' })
.select([
'user.id', 'user.name', 'user.email' // User
'role.name AS rName' // Roles
'user_profile.id AS pId', 'user_profile.date_of_birth AS pDob' // UserProfiles
'auth_token.id AS atId' 'auth_token.platform AS atPlatform', 'auth_token.token AS atToken' // AuthTokens
])
.leftJoin('user_profile', 'user_profile.user_id', 'user.id')
.leftJoin('user_role', 'user_role.user_id', 'user.id')
.leftJoin('role', 'role.id', 'user_role.role_id')
.leftJoin('auth_token', 'auth_token.user_id', 'user.id')
.then(users => {
users = users.filter(user => {
return user.pApp_id === appId && user.atApp_id === appId && user.atPlatform === platform;
});
return users;
});
这会产生与 SQL 查询相同的结果,但问题是我必须在 Knex 调用的 .then() 子句中过滤返回的用户,因为我不知道如何添加 WHERE 条件Application.name 和 AuthToken.platform。
问题:
谁能帮我弄清楚如何构造我的 Knex 代码的 .where() 子句以使其与 SQL 查询等效?
注意事项:
- 我不知道如何
console.logKnex 生成的 SQL 查询,因此我不完全确定我当前的 Knex 代码是否会在它上面生成 SQL 查询(减去正确的WHERE子句)。通过在 PgAdmin 中运行查询并console.log()ing 从 Knex 函数返回的users,我已经检查过它确实返回了相同的结果。 - 我没有包含定义此问题中使用的表和列的
CREATE TABLE/ Knex 迁移,因为对我来说这没有必要,我不想让已经很长的问题变得更长.但是,如果您需要查看它,请不要犹豫,让我知道。我很乐意将其包括在内。
【问题讨论】:
-
你能把它变成一个过程并传递一个输入吗?似乎是一个更好的过程。
-
@Jacob_H 这听起来很有趣。您是否有一些资源可供我参考?
标签: sql node.js postgresql knex.js