Search code examples
swiftrelationshipvaporvapor-fluent

Vapor 4 parent child relationship


In Vapor 4 I have created a user and it has "gear" as such:

final class User: Model, Content {

    init() {}

    static var schema: String = "user"

    @ID(key: .id)
    var id: UUID?

    @Field(key: "name")
    var name: String?

    @Children(for: \.$user)
        var gear: [Gear]
}


final class Gear: Model, Content {

    init() {}

    static var schema: String = "gear"

    @ID(key: .id)
    var id: UUID?

    @Parent(key: "userId")
    var user: User
}

Then when I get this data I do:

func index(req: Request) throws -> EventLoopFuture<[User]> {
    return User.query(on: req.db).with(\.$gear).all()
}

Rather smooth and simple. Except that ID is being forced to be an UUID while the table in the database can only take the type "text" so I get the error:

{
    "error": true,
    "reason": "server: operator does not exist: text = uuid (op_error)" 
}

So anyone have a clue of how to solve this?

The structure I want in response is similar to:

{
    "id": "w32423tsdg3w",
    "name": "username",
    "gear": [{
        "id": "1"
        },
        {
        "id": "2"
        }
    ]
}

Solution

  • In this case ID should be set as String

    @ID(key: .id, generatedBy: .user) var id: String?