steam 3 Fluent-mysql 连接查询

标签 vapor vapor-fluent fluent-mysql

如何在Vapor 3中使用 Fluent-mysql 进行联接查询和限制查询?例如:

在 a.id = b.aid LIMIT 0,10 上选择 a.*, b.*

我没有找到这样的例子和文档。

最佳答案

你可以像这样使用 FluentMySQL 来做到这一点

func something(_ req: Request) throws -> Future<HTTPStatus> {
    return User.query(on: req)
               // this is how you can join anything
               .join(\Token.userId, to: \User.id)
               // this is how you can filter values
               .filter(\Token.createdAt, .lessThan, Date())
               // this is how to apply LIMIT and OFFSET
               .range(lower: 0, upper: 10)
               // this is how to decode joined model
               .alsoDecode(Token.self)
               // requests an array of results (or use .first if you need only one first row)
               .all().map { results in
        for (user, token) in results {
            print("user: \(user.firstName) token: \(token.token)")
        }
        return .ok
    }
}

或者您可以使用 SwifQL library 构建原始查询然后像这样执行

func something2(_ req: Request) throws -> Future<HTTPStatus> {
    // build your query like you do in raw SQL
    let query = SwifQLSelectBuilder().select(User.table.*)
                                     .from(User.table)
                                     .join(.left, Token.table, on: \Token.userId == \User.id)
                                     .where(\Token.createdAt < Fn.now())
                                     .offset(0)
                                     .limit(10)
                                     .build()
    // this way you could print raw query to execute it in mysql manually for debugging purposes
    print("raw query: " + query.prepare(.mysql).plain)
    // executes query with mysql dialect
    return query.execute(on: req, as: .mysql)
                // requests an array of results (or use .first if you need only one first row)
                // You also could decode query results into the custom struct
                .all(decoding: User.self).map { users in
        return .ok
    }
}

关于steam 3 Fluent-mysql 连接查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55275018/

相关文章:

postgresql - 如何在 Vapor 3/Fluent 中记录 SQL 语句?

swift - 使用 vapor-fluent 更新模型

swift - Vapor参数解码挂起HTTP请求

Vapor 4流利。复杂查询、过滤、不存在则创建

swift - Vapor Swift 如何删除从 fileIO 收集的文件

swift - 在 Vapor 中使用 Fluent 时连接崩溃

swift - 不支持 MySQL & Vapor 3 : unrecognized basic packet, 完整身份验证

swift - 使用 Vapor 4 中的协议(protocol)进行通用流畅查询