nanana
nanana

Reputation: 77

How do you define multiple UUID in a model

I am using Vapor and Fluent. I want to define a user model like below, but I get an error saying:

Fatal error: Error raised at top level: previousError(server: multiple primary keys for table "users" are not allowed

Is it not possible to define multiple UUIDs in one model?

import Vapor
import FluentPostgresDriver

final class User: Model, Content {
    static let schema = "users"

    @ID(custom: "id")
    var id: Int?
    
    @Field(key: "email")
    var email: String
    
    @Field(key: "password")
    var password: String
    
    @ID(custom: "public_id")
    var public_id: UUID?

    init() { }


    init(id: Int? = nil,email: String, password:String, public_id: UUID? = nil) {
        self.id = id
        self.email = email
        self.password = password
        self.public_id = public_id
    }
}

struct CreateUser: Migration {
    func prepare(on database: Database) -> EventLoopFuture<Void> {
        database.schema("users")
            .field("id", .int, .identifier(auto: true))
            .field("email", .string)
            .field("password", .string)
            .field("public_id", .uuid,?????)
            .create()
    }
.....
}

Upvotes: 0

Views: 316

Answers (1)

PaulProgrammer
PaulProgrammer

Reputation: 17710

Instead of marking the public UUID as @ID, just mark it as another @Field (string type is easiest, but you can also do binary [16 bytes] if you're feeling like wearing a propeller beanie), and make it required.

During the create, you'll have to actually invoke a UUID generation function, but that ought to be easy enough.

But, why not make the primary key the UUID, instead of having two identifiers? It takes a little more room in the database, but might be worth avoiding the headache of having several different ids.

Upvotes: 1

Related Questions