Reputation: 1498
I have a database with some complex relationships mapped and populated with a large amount of data. My requirement is that I need to use this database with Swift-Vapor server.
So that I created a model object (with Fluent framework constructs) similar to the database schema, in order to handle data flows between the vapor server and db.
When it comes the time to link database table(users table) with the model(User model), I found this method, which should implement inside the model class.
static func prepare(_ database: Database) throws {
try database.create("users") { users in
users.id()
users.string("name")
}
}
Since I don't need to define a schema for already existing db, this prepare method just left unimplemented.
The result is that I just can't interact with db, for any operations like userObj.save()
The same thing I achieved with Swift-Perfect Server with the help of the following method implementation inside the model object. This was done with the help MySQLStORM
in Perfect.
// Map the model to the database table "user"
override open func table() -> String {
return "user"
}
What I'm looking for is ->
Is there any option like this available in Vapor so that I can map model object to a database table?
Upvotes: 1
Views: 708
Reputation: 1498
Got a solution while discussing this issue in Slack community, tried out and working fine.
Solution:
In the model class (say User
), the prepare
method can be left unimplemented, like
static func prepare(_ database: Database) throws {
}
But should add a static variable entity
which will have the table name mapped, like
final class User: Model {
static let entity = "users"
...
}
And finally, we should add the model to the droplets preparations array, like
// Let the User be your model object
drop.preparations.append(User.self)
So that we can use any existing database with complex relations or pre-populated data tables to map with the model object, without constructing tables from model object.
Upvotes: 3