在Fluent + Vapor中查询子项

Gar*_*yle 8 fluent vapor

我对如何查询模型对象的子项并立即使用它感到困惑.我ClientStation儿子很多

final class Client: PostgreSQLModel {
    var stations: Children<Client, Station> {
        return children(\.clientID)
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在我的控制器中,我有一个客户列表,我想看看并抓住他们的电台.

func clientIndexHandler(_ req: Request) throws -> Future<View> {
    return Client.query(on: req).all().flatMap(to: View.self) { clients in
        let sorted = clients.sorted { ... }
        let content = try sorted.map { client in
            let stations = try client.stations
                                       .query(on: req)
                                       .all()
                                       .map(to: [String].self) { stations in
                return stations.map { $0.name }
            }

            // Now I want to use the stations for other stuff.

            return ClientIndexContent(client: client, stations: stations, ....)
        }

        let context = ClientIndexContext(clients: content)
        return try req.make(LeafRenderer.self).render("clients/index", context)
    }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是,stationsEventLoopFuture<[String]>不是一个[String].由于我在这里使用Leaf,我需要来自客户端和工作站的实际值,以便我可以填充内容以传递到叶子渲染器.

0xT*_*Tim 1

所以你有很多方法可以做到这一点,但基本上你需要重新思考如何在异步世界中做事。然而,Vapor 确实提供了一些很好的东西来帮助实现这一点。首先,Leaf 实际上可以处理 future,因此如果您将 your 设置ClientIndexContext为具有 属性let stations: Future<[String]>,那么您可以像平常一样在 Leaf 内部访问该属性。

您可以做的另一个选择是致电,map(to: [String].self)stations将为您获得所有期货。