如何在Vapor 3中使用fluent-mysql联接查询和限制查询?例如:
SELECT a.*, b.* ON a.id = b.aid LIMIT 0,10
我找不到此类示例和文档。
答案 0 :(得分:0)
您可以像这样用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
}
}