将多个联接与Vapor中的过滤器结合

时间:2019-03-22 22:38:26

标签: mysql swift join vapor

在我的后端,我有Post和一个PostController。帖子可能是visibleToFriendOnly
GET /posts中,我想返回允许当前用户查看的所有帖子。
User模型具有friends属性,这是User, User的枢纽,其中包含列userIDfriendID

我目前收到这样的帖子:

/// /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()
}

我为此很难,因为对于每个Post,我必须先得到userID,然后得到User(作者),然后查询用户的friends,然后查看当前用户是否在该列表中。
有可行的方法吗?也许是加入还是其他?

1 个答案:

答案 0 :(得分:1)

看起来您可以像这样构建自定义原始查询

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)
}