swift vapor3新连接的原始sql查询

ztyzrc3y  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(288)

我正在尝试使用vapor3执行原始sql查询。不幸的是,网站上提供的这类东西的文档非常模糊。
基本上我想做一些事情,比如:

router.get("example") { req -> Future<View> in
    let leaf = try request.make(LeafRenderer.self)

    // I can't get this next bit to work. Does anyone have any ideas how to do this? I seem to get all sorts of Xcode errors with .mysql, closures etc.
    let users = try request.withNewConnection(to: .mysql) { connection -> EventLoopFuture<[User]> 
       return try connection.raw("select * from users").all(decoding: User.self)
    }

    var context = [String: String]()
    context["user"] = users

    return leaf.render("example", context)
}

如果你能帮我解决这个问题,我将不胜感激。
谢谢你,马特

nvbavucw

nvbavucw1#

代码失败是因为没有正确实现闭包。你的路线在 let users... 所以第二次 return 永远无法到达。
这样做有效:

router.get("example")
{
    insecure.get("example") {
        request -> Future<View> in
        return request.withNewConnection(to: .mysql) {
            connection in
            return connection.raw("select * from User").all(decoding: User.self).flatMap(to:View.self) {
                users in
                return try request.make(LeafRenderer.self).render("example",["users":users])
            }
        }
    }
}

这些变化是:
不需要定义 leaf 直到你需要它。
定义 users 现在已经进入关闭状态了。

相关问题