Hello, I need help to eagerly-load nested data. This is a simplified version of the models:
final class User: Model, Content, Equatable, Sendable {
@ID(key: .id) var id: UUID?
@Children(for: \.$user) var joinedInstitutions: [InstitutionEntity]
}
final class InstitutionEntity: Model, Content, Equatable, Hashable {
@ID(key: .id) var id: UUID?
@Parent(key: "institutionID") var institution: Institution
}
final class Institution: Model, Content, Equatable, Hashable, Sendable {
@ID(key: .id) var id: UUID?
@Timestamp(key: "created_at", on: .create) var createdAt: Date?
@Timestamp(key: "updated_at", on: .update) var updatedAt: Date?
}
When I load a User, I'd like to load all its joinedInstitutions, and in turn, each of the joinedInstitution's institution. I have tried the following:
extension Request {
func loadUserWithACLInfo() async throws -> User {
/**
Verify the user has an `id`
*/
let userID = try auth.require(User.self).requireID()
/**
Load the user with `joinedInstitutions`
*/
guard let userWithACLInfo = try await User
.query(on: db)
.filter(\.$id == userID)
.with(\.$joinedInstitutions) { joinedInstitution in
joinedInstitution.with(\.$institution)
}
.first() else {
throw Abort(.notFound, reason: "User not found")
}
return userWithACLInfo
}
}
But I get the following error:
Cannot find 'joinedInstitution' in scope
Any ideas?
to @cunning niche, who now has 1137