2

使用Vapor我想存储与孩子的关系。我还没有找到任何类应该是什么样子的例子,我只是在猜测该怎么做。谁能提供一个与其他Model对象列表有关系的类的示例?

import Vapor
import Fluent
import Foundation

final class Store: Model {

    // MARK: - Model
    var id: Node?
    var exists: Bool = false
    var locationIDs: [Node] = [] // No idea if this is right

    var name: String

    init(name: String, locationIDs: [Node] = []) {
        self.id = nil
        self.name = name
        self.locationIDs = locationIDs
    }

    init(node: Node, in context: Context) throws {
        id = try node.extract("id")
        name = try node.extract("name")
//      ???
    }

    func makeNode(context: Context) throws -> Node {
        return try Node(node: [
            "id": id,
            "name": name
//          ???
        ])
    }

    static func prepare(_ database: Database) throws {
        try database.create( "stores" ) { creator in
            creator.id()
            creator.string("name")
//            creator.id("", optional: false) // ???
        }
    }

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

}
4

1 回答 1

1

这是我对用户和组关系的实现。一个用户属于一个组并且组有很多用户,所以一个简单的 1 -> Many 关系。

final public class User: Model {
  public var id: Int?
  var emailAddress: String
  var username: String
  var groupId: Int

}

extension User {
  var group: Parent<User, Group> {
    return parent(\.groupId)
  }
}


final public class Group: Model {
   public var id: Int?
   var name: String
}

extension Group {
   var users: Children<Group, Users> {
      return children(\.groupId)
   }
}

许多 <-> 许多是相似的,但在关系的中间使用了数据透视表。

于 2019-06-25T21:05:21.867 回答