vapor 3 fluent-mysql 加入查询
vapor 3 fluent-mysql join query
如何在Vapor 3中使用fluent-mysql加入查询和限制查询?例如:
SELECT a.*, b.* ON a.id = b.aid LIMIT 0,10
我没有找到这样的例子和文档。
你可以像这样用 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
}
}
如何在Vapor 3中使用fluent-mysql加入查询和限制查询?例如:
SELECT a.*, b.* ON a.id = b.aid LIMIT 0,10
我没有找到这样的例子和文档。
你可以像这样用 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
}
}