我想在 Vapor 4 中建立aLeague
和 a之间的父子关系。我可以创建一个就好了,但是当我尝试像这样创建一个新团队时:Team
League
{
"name": "Chicago Bulls",
"league_id": "C21827C2-8FAD-4A89-B8D3-A3E62E421258"
}
我收到此错误:
{
"error": true,
"reason": "Value of type 'League' required for key 'league'."
}
我只想用从表中引用 a的Team
a来初始化 a 。我在 Vapor 3 中进行了这项工作,但在 Vapor 4 中似乎无法做到这一点。league_id
League
Leagues
请参阅下面的模型和迁移。
League
模型:
final class League: Model, Content {
init() {}
static let schema = "Leagues"
@ID(key: .id) var id: UUID?
@Field(key: .name) var name: String
@Field(key: .sport) var sport: String
@Children(for: \.$league) var teams: [Team]
init(name: String, sport: String) {
self.name = name
self.sport = sport
}
}
Team
模型:
final class Team: Model, Content {
init() {}
static let schema = "Teams"
@ID(key: .id) var id: UUID?
@Field(key: .name) var name: String
@Parent(key: .leagueId) var league: League
init(id: UUID? = nil, name: String, leagueId: UUID) throws {
self.id = id
self.name = name
self.$league.id = leagueId
}
}
CreateLeague
移民:
struct CreateLeague: Migration {
func prepare(on database: Database) -> EventLoopFuture<Void> {
return database.schema(League.schema)
.id()
.field(.name, .string, .required)
.field(.sport, .string, .required)
.create()
}
func revert(on database: Database) -> EventLoopFuture<Void> {
return database.schema(League.schema).delete()
}
}
CreateTeam
移民:
struct CreateTeam: Migration {
func prepare(on database: Database) -> EventLoopFuture<Void> {
return database.schema(Team.schema)
.id()
.field(.name, .string, .required)
.field(.leagueId, .uuid, .required, .references(League.schema, .id))
.create()
}
func revert(on database: Database) -> EventLoopFuture<Void> {
return database.schema(Team.schema).delete()
}
}
TeamsController
:
class TeamsController: RouteCollection {
func boot(routes: RoutesBuilder) throws {
let teamsRoute = routes.grouped("teams")
teamsRoute.post(use: createTeam)
}
func createTeam(req: Request) throws -> EventLoopFuture<Team> {
let team = try req.content.decode(Team.self)
return team.save(on: req.db).map { team }
}
}