[英]Combine multiple joins with filters in Vapor
In my backend, I have Post
s and a PostController
.在我的后端,我有
Post
和一个PostController
。 A post may be visibleToFriendOnly
.帖子可能是
visibleToFriendOnly
。
In GET /posts
, I want to return all posts that the current user is allowed to see.在
GET /posts
,我想返回允许当前用户查看的所有帖子。
The User
model has a friends
property, that is a pivot of User, User
with the columns userID
and friendID
. User
模型有一个friends
属性,它是User, User
的数据透视表,包含userID
和friendID
列。
I currently get posts like this:我目前收到这样的帖子:
/// /posts
func all(req: Request) throws -> Future<[Post]> {
let authenticated = try req.requireAuthenticated(User.self)
return Post.query(on: req)
.filter(\Post.visibleForUserType == authenticated.type)
// FIXME: respect .visibleForFriendsOnly
.all()
}
I'm having a hard time with this because for each Post
, I'd have to get the userID
and then the User
(who is the author) and then query the user's friends
and see whether the current user is in that list.我对此感到很困难,因为对于每个
Post
,我必须先获取userID
,然后获取User
(作者是谁),然后查询用户的friends
并查看当前用户是否在该列表中。
Is there a feasible way of doing this?有没有可行的方法来做到这一点? Maybe a join or something?
也许加入什么的?
It looks like you could build a custom raw query like this看起来您可以像这样构建自定义原始查询
return req.requestPooledConnection(to: .mysql).flatMap { conn in
defer { try? req.releasePooledConnection(conn, to: .mysql) }
return conn.raw("""
SELECT posts.* FROM posts
LEFT OUTER JOIN user_friends
ON (user_friends.userID = posts.userID AND user_friends.friendID = 3)
OR (user_friends.friendID = posts.userID AND user_friends.userID = 3)
GROUP BY posts.id
HAVING COUNT(user_friends.id) = 2 OR posts.userID = 3 OR visibleForFriendsOnly = 0
""").all(decoding: Post.self)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.