1

我想查询在兄弟姐妹字段中包含某些用户的聊天。

简化模型:

final class Chat: Model, Content {

  @Siblings(through: ChatUser.self, from: \.$chat, to: \.$user)
  var users: [User]

}

final class User: Model, Content {

  @Siblings(through: ChatUser.self, from: \.$user, to: \.$chat)
  var chats: [Chat]
}

我的获取路线:

func fetch(req: Request) throws -> EventLoopFuture<[Chat]> {

    let user = try req.auth.require(User.self)

    return Chat
      .query(on: req.db)
      .filter("users", .contains(inverse: false, .anywhere), user)
      .all()
}

我明白了[ ERROR ] server: column chats.users does not exist (errorMissingColumn)

我怎样才能以正确的方式做这样的过滤器?

4

1 回答 1

1

如果我正确理解了您的要求,那么您应该从User最后的兄弟关系开始,而不是Chat. 您的查询然后简化为:

func fetch(req: Request) throws -> EventLoopFuture<[Chat]> {

    let user = try req.auth.require(User.self)

    return User
      .query(on: req.db)
      .filter(\.$id == user.id!)
      .with(\.$chats)
      .first()
      .unwrap(or:Abort(.internalServerError))
      .map
      {
           chattyUser in
           return chattyUser.chats
      }
}
于 2020-06-04T15:53:41.040 回答