我正在尝试查询与两个用户的聊天。如果它存在,我想退货。如果不是,我想与这两个用户创建新的聊天并将其返回。
如果聊天存在,评论会显示失败的地方。
如果您可以展示如何在这种情况下与这两个用户创建新的聊天,也会很有帮助。
func create(req: Request) throws -> EventLoopFuture<Chat> {
let currentUser = try req.auth.require(User.self)
guard
let userID = req.parameters.get("userID"),
let uuid = UUID(userID)
else { throw Abort(.badRequest) }
return User
.query(on: req.db)
.filter(\.$id == uuid)
.with(\.$chats)
.first()
.unwrap(or: Abort(.internalServerError))
.flatMap({ chatUser -> EventLoopFuture<Chat> in
let chat = chatUser
.chats
.filter({
$0.users.contains(where: { $0.id == currentUser.id }) // FAILS HERE: Fatal error: Siblings relation not eager loaded, use $ prefix to access: Siblings<Chat, User, ChatUser>(from: [chat_id], to: [user_id]): file
})
.first
if let chat = chat {
return req
.eventLoop
.makeSucceededFuture(chat)
} else {
// create new chat with those two users and return
}
})
}
简化模型:
final class Chat: Model, Content {
@ID(key: .id)
var id: UUID?
@Siblings(through: ChatUser.self, from: \.$chat, to: \.$user)
var users: [User]
}
final class User: Model, Content {
@ID(key: .id)
var id: UUID?
@Siblings(through: ChatUser.self, from: \.$user, to: \.$chat)
var chats: [Chat]
}
final class ChatUser: Model {
@ID(key: .id)
var id: UUID?
@Parent(key: Keys.chatId)
var chat: Chat
@Parent(key: Keys.userId)
var user: User
}