steam 3 fluent-mysql запрос на присоединение - PullRequest
1 голос
/ 21 марта 2019

Как использовать fluent-mysql для объединения запросов и ограничения запросов в Vapor 3? например:

SELECT a.*, b.* ON a.id = b.aid LIMIT 0,10

Я не нахожу таких примеров и документов.

1 Ответ

0 голосов
/ 21 марта 2019

Вы можете сделать это с помощью 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-библиотеку и выполнить его следующим образом

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