简体   繁体   English

在 Vapor 中将多个连接与过滤器相结合

[英]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的数据透视表,包含userIDfriendID列。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM