1

我尝试从 mySQL 请求一些数据来呈现带有叶子的表。

由于 Futures,我不知道如何结合 FluentMySQL 和 Leaf。

import Vapor

final class IndexController {
    func index(_ req: Request) throws -> EventLoopFuture<View>{
        let futureEvents = try Event.query(on: req).all()

        // Here I want to add the querys results to 'renderParameters'
        var renderParameters = ...

        return try req.view().render("index", renderParameters)
    }
}
4

1 回答 1

2

使用问题中的代码很难给你答案,但希望这会给你足够的指导让你继续前进。

创建一个结构来保存要从查询结果发送到视图的信息到View. 确保它是Encodable. 我没有使用 的简单示例Future,但类似以下内容可以轻松包含[Future<Location>]

struct AllLocationsContext: Encodable {
    let title: String
    let hideInactiveLocations: Bool
    let locations: [Location]
}

然后将 a 添加flatMap到您的查询中并嵌入参数结构的创建和return创建View.

locations.get("/")
{
    request -> Future<View> in
    let title = "Events (Active and Inactive)"
    return Location.query(on:request).sort(\.name).all().flatMap(to: View.self)  {
        locations in
        let context = AllLocationsContext(title: title, hideInactiveLocations: hideInactiveLocations, locations: locations)
        return try request.view().render("locations",context)
    }
}
于 2019-01-02T17:16:46.777 回答