Vapor 数据持久化的简单介绍以及Fluent的使用

关于web框架、这里使用vapor

使用 vapor --help 命令我们可以看到有几种模板可供我们使用。

  • 这里也主要是使用这些来搭建。

Api模板

vapor new Hello --template=api

Web模板

vapor new Hello --template=api

因为有模板,所以会简单很多。

这里不再进行编写ORM,这里介绍一下vapor的Fluent

如果出错可以看官方文档

  • Fluent provides an easy, simple, and safe API for working with your persisted data. Each database table/collection is represented by a Model that can be used to interact with the data. Fluent supports common operations like creating, reading, updating, and deleting models. It also supports more advanced operations like joining, relating, and soft deleting.

谷歌翻译一下,大致如下。

  • Flunet提供了一个容易,简单,安全的API来处理你的持久数据。 每个数据库表/集合由可用于与数据交互的模型表示。 Fluent支持常见操作,如创建,读取,更新和删除模型。 它还支持更高级的操作,如加入,关联和软删除。

反正就是不用自己写SQL语句就能进行数据的增删改查。

创建一个Model

  • 这里是OC NSKeyedArchiver(归档) 差不多,需要实现一个协议。
final class Pet: Model {
    var name: String
    var age: Int
    let storage = Storage()

    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }

    init(row: Row) throws {
        name = try row.get("name")
        age = try row.get("age")
    }

    func makeRow() throws -> Row {
        var row = Row()
        try row.set("name", name)
        try row.set("age", age)
        return row
    }
}

Storage

  • 存储属性允许添加额外的属性,比如数据库id

  • The storage property is there to allow Fluent to store extra information on your model--things like the model's database id.

Row

The Row struct represents a database row. Your models should be able to parse from and serialize to database rows.

Preparing the Database

In order to use your model, you may need to prepare your database with an appropriate schema.

Preparation

  • Most databases, like SQL databases, require the schema for a model to be created before it is stored. Adding a preparation to your model will allow you to prepare the database while your app boots.

  • 大多数数据库都要求在存储数据之前创建模型。所以这里需要预处理

extension Pet: Preparation {
    static func prepare(_ database: Database) throws {
        try database.create(self) { pets in
            pets.id()
            pets.string("name")
            pets.int("age")
        }
    } 

    static func revert(_ database: Database) throws {
        try database.delete(self)
    }
}

其他更多用法可以看官方文档

Fluent文档

你可能感兴趣的:(Vapor 数据持久化的简单介绍以及Fluent的使用)