3

我想在 Vapor 4 中建立aLeague和 a之间的父子关系。我可以创建一个就好了,但是当我尝试像这样创建一个新团队时:TeamLeague

{
    "name": "Chicago Bulls",
    "league_id": "C21827C2-8FAD-4A89-B8D3-A3E62E421258"
}

我收到此错误:

{
    "error": true,
    "reason": "Value of type 'League' required for key 'league'."
}

我只想用从表中引用 a的Teama来初始化 a 。我在 Vapor 3 中进行了这项工作,但在 Vapor 4 中似乎无法做到这一点。league_idLeagueLeagues

请参阅下面的模型和迁移。

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

}
4

1 回答 1

9

这是失败的,因为属性包装器覆盖模型的 JSON 解码的方式。你有两个选择。您可以发送 JSON Fluent 期望:

{
    "name": "Chicago Bulls",
    "league": {
        "id": "C21827C2-8FAD-4A89-B8D3-A3E62E421258"
    }
}

或者,您可以创建一个CreateTeamData与您希望发送的 JSON 匹配的新类型,然后手动创建一个Team。我更喜欢第二条路线:

struct CreateTeamData: Content {
  let name: String
  let leagueID: UUID
}

func createTeam(req: Request) throws -> EventLoopFuture<Team> {
    let data = try req.content.decode(CreateTeamData.self)
    let team = Team(name: data.name, leagueID: data.leagueID)
    return team.save(on: req.db).map { team }
}
于 2020-06-16T15:27:02.410 回答