vapor-使用Alsodecode()从mysql获取数据 [英] vapor - Obtaining data from mysql using alsodecode()

查看:69
本文介绍了vapor-使用Alsodecode()从mysql获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从MySQL数据库中获取数据,该数据库使用功能AlsoDecode()将我的两个表(Uusario和Colegios)连接在一起.

I'm trying to obtain data from a mysql database joining two of my tables (usuarios and colegios) with the function alsodecode().

我的代码如下:

func usuariosHandler(_ req: Request) throws -> Future<View> {
        return Usuario.query(on: req).join(\Colegio.id, to: \Usuario.colegioId).alsoDecode(Colegio.self).all().flatMap(to: View.self) { usuarios in
            let contexto = UsuariosContext(title: "Usuarios de la aplicación", usuarios: usuarios)
            return try req.view().render("usuarios", contexto)
        }
    }

问题在于查询的结果是一个元组,我必须通过叶将其发送到视图.此外,这是编译器的错误:无法将类型[[(Usuario,Colegio)]]的值转换为预期的参数类型'[Usuario]'

The problem is that the result of the query is a tuple that I have to send to a view through leaf. In addition, this is the error into the compiler: Cannot convert value of type '[(Usuario, Colegio)]' to expected argument type '[Usuario]'

我是Swift和Vapor的初学者.有人可以帮我吗?

I'm a beginner of Swift and Vapor. Can anybody help me with this?

谢谢!

推荐答案

您需要使用 Encodable 结构传递元组-一种结构用于保存元组数据,另一种用于上下文:

You need to use an Encodable structure to pass tuples - one structure to hold the tuple data and one for the context:

struct MyTuple: Encodable {
    let name: String // put the fields from the join in here
}

struct MyContext Encodable {
    let title: String
    let usuarios: [MyTuple]
}

Then modify your route to create the data structure to pass as the context:

func usuariosHandler(_ req: Request) throws -> Future<View> {
    return Usuario.query(on: req).join(\Colegio.id, to: \Usuario.colegioId).alsoDecode(Colegio.self).all().flatMap(to: View.self) { usuarios in
        var usuariosTuples: [MyTuple] = []
        for usuario in usuarios {
            usuariosTuples.append( MyTuple( usuario.0 ) )
        } 
        let contexto = UsuariosContext(title: "Usuarios de la aplicación", usuarios: usuariosTuples)
        return try req.view().render("usuarios", contexto)
    }
}

我假设第一个字段是 string .

这篇关于vapor-使用Alsodecode()从mysql获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆