我有一个SQL查询(Postgres),其中包含几个join我无法转换为单个Knex.js语句的。这是SQL查询:
join
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查询相同的结果,但是问题是我必须.then()在Knex调用的子句中过滤返回的用户,因为我不知道如何WHERE为Application.nameand添加条件AuthToken.platform。
.then()
WHERE
Application.name
AuthToken.platform
问题:
有人可以帮我弄清楚如何构造我的Knex代码的.where()子句,使其等同于SQL查询吗?
.where()
笔记:
console.log
console.log()
users
CREATE TABLE
要调试,您可以.toSQL()用来调试knex查询文档。 另外,漂亮的速查表
.toSQL()
作为热修复解决方案,您可以在其中使用.raw()并粘贴SQL代码。
.raw()
关于WHERE条件,您可以将它们链接在knex查询的末尾。 像这样的东西:
return knex('user') .select('user.id', 'user.name', 'user.email', 'role.name AS rName' 'user_profile.id AS pId', 'user_profile.date_of_birth AS pDob', 'auth_token.id AS atId' 'auth_token.platform AS atPlatform', 'auth_token.token AS atToken' ) .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') .where('user.email', 'like', '%some@email.com%') .andWhere('application.name', 'like' '%awesome-application%') //...etc