0
votes

I'm trying to setup parenting within an app (Vapor 4) and although its achievable, I have run across the issue or at least a limitation that results in less meaningful property names being used within the Model.

Vapor 4 requires the @ID property to be named 'id' (var id: ...), whereas in previous version the property name was definable and therefore more meaningful name.

For example the User table: Our user data uses the Username as a unique key (not the primary key) so the User model is defined as such:

  // 'Unique key for the record.'
  @ID(custom: "sysid", generatedBy: .database)
  var id: Int?

  // Unique login name 
  @Field(key: "username")
  var username: String?

  // Password for this login.
  @Field(key: "password")
  var password: String
  ...

Makes sense and is readable, and anywhere the Model is used within the App the dev knows the Id Field is the sysid and the username is the username.

The Foreign key's in the Rule and Profile table's use Username as the foreign key (because of legacy reasons). To change it though-out the db and app is not currently possible.

Since the original implementation I have been reading up and realised the benefits of using relationships (rather than Filters and Joins).

To use relationships within Vapor 4 I have to change the Model definition to:

  // 'Unique key for the record.'
  @Field(key: "sysid")
  var sysid: Int?

  // Unique login name 
  @ID(key: "username")
  var id: String?

  // Password for this login.
  @Field(key: "password")
  var password: String
  ...

My Model definitions are less meaningful (although it does work):

Of course this means though-out the code .username now needs to be changed to .id which is far less self-explanatory.

In Vapor 3 we could define the ID Property Name to anything. It would be much easier if Fluent/Vapor 4 allowed custom Property Names like in previous versions.

I was wondering if anyone has come across this 'issue?' or has a workaround to allow the Models to continue to use meaningful names and still allow Parenting to work correctly.

I used this simple user data as an example but surely others use different/meaningful column names that suffer my .. annoyance?

Any guidance/thoughts would be appreciated Thanks

1

1 Answers

1
votes

Fluent's relationship property wrappers are all based on the relationship being defined under the id property. This allows you to create a child with just the parent ID and without having to look up the parent in the DB first etc.

If you want to use something other than the ID, you'll need to either just perform the queries manually (which for parent/child is relatively simple) or duplicate the property wrappers and choose a different property.