Address

Let's add an address by following these steps:

  1. Create an Address.swift file in Sources/App/Models/Database/ and enter the following content:
import Vapor
import Fluent

final class Address: Model {

static let schema = "addresses"

@ID(key: "id")
var id: Int?

@Field(key: "street")
var street: String

@Field(key: "city")
var city: String

@Field(key: "zip")
var zip: String

@Timestamp(key: "createdAt", on: .create)
var createdAt: Date?
@Timestamp(key: "updatedAt", on: .update)
var updatedAt: Date?
@Timestamp(key: "deletedAt", on: .delete)
var deletedAt: Date?

init() {
}
}

You can see that we are also storing the basic properties (street, city, zip) in the class. Just as with User, we have given Address the correct dependencies and customized the table name through schema.

To keep it simple, we are assuming that we only need the street, ZIP, and city as properties for an address. In a real-world application, you would certainly want to use more properties (such as country, and so on) to specify an address. Check out this article to learn more: https://www.mjt.me.uk/posts/falsehoods-programmers-believe-about-addresses/.

We do want an address connected to a User, so we will create a userId property that saves the user's ID.

  1. Add the following lines after the zip property:
@Field(key: "userId")
var userId: Int
  1. Adjust the constructor to look like this:
    init(street: String, city: String, zip: String, userId: Int) {
self.street = street
self.city = city
self.zip = zip
self.userId = userId
}

Since userId is not optional, we always need it when creating a new instance. This is by design so that no addresses can exist without a user connection.

This function is now taking the userId field and connects it to the User.id property. That way, the two models are connected, both logically and in the database.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.174.133