gpt4 book ai didi

fluent - 在 Fluent+Vapor 中查询子项

转载 作者:行者123 更新时间:2023-12-03 02:02:26 31 4
gpt4 key购买 nike

我对如何查询模型对象的子对象并立即使用它感到困惑。我的Client包含数量Station child

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

然后在我的 Controller 中,我有一个我想要查看并获取他们的电台的客户端列表。

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

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

最佳答案

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

您可以做的另一个选择是调用 map(to: [String].self)stations这将为您带来所有的 future 。

关于fluent - 在 Fluent+Vapor 中查询子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49992464/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com