简体   繁体   English

Swift + Firestore:如何获取相关对象

[英]Swift + Firestore: How to fetch related objects

I have this model in Swift我在 Swift 中有这个模型

import SwiftUI
import FirebaseFirestoreSwift
import FirebaseFirestore

struct Tweet: Codable, Identifiable, Hashable {
        
    var id: UUID = UUID()
    var content: String
    var ownerId: String
    var owner: UserProfile
    var likes: Int
    @ServerTimestamp var createdAt: Timestamp?
}

and it's stored in Firestore collection "tweets":它存储在 Firestore 集合“推文”中:

tweets: {
    [
        "ds4a65d4a65sd46das65d4": {
            "content" : "safsafds",
            "createdAt" : "...",
            "id" : "sdfsdfsd",
            "likes" : 0,
            "ownerId" : "123",
            "owner" : {
                 "bio": "aaasdasdassa",
                 "username": "asdasd",
                 "profileImage": "aaa",
                 "userId": "123",
             },
        }, ... 
    ]
}

When I fetch all tweets, I get the information normally, with the owner data.当我获取所有推文时,我会正常获取带有所有者数据的信息。 but the owner data could be old.但所有者数据可能是旧的。 say that the user has changed his profile image, or username...etc, so the tweets owners data could be not up-to-date.假设用户更改了他的个人资料图片或用户名...等,因此推文所有者数据可能不是最新的。

So, assuming that we want to remove the owner field from the tweet model, and keep the ownerId.因此,假设我们要从推文模型中删除 owner 字段,并保留 ownerId。

How to fetch all the tweets with the owners' data using the following model?如何使用以下模型获取包含所有者数据的所有推文?

struct Tweet: Codable, Identifiable, Hashable {
        
    var id: UUID = UUID()
    var content: String
    var ownerId: String
    // var owner: UserProfile   <-- THIS IS REMOVED
    var likes: Int
    @ServerTimestamp var createdAt: Timestamp?
}

Considering, the most basic example is when your object only has simple data types.考虑一下,最基本的例子是当你的对象只有简单的数据类型时。

            {
              "name": “Sam’s website”,
              "hits": “200”
             }

The corresponding Swift struct could look like this:相应的 Swift 结构可能如下所示:

Struct Website: Identifiable, Codable{
           @DocumentID public let id: String?
           let name: String
           let hits: Int
         }

To get your Firestore object into Swift, you need to use the .data(as: ) method.要将 Firestore 对象导入 Swift,您需要使用 .data(as:) 方法。 In the scenario below, I am getting all the documents in the Firestore collection websites and putting them into a property called self.websites在下面的场景中,我获取 Firestore 集合网站中的所有文档并将它们放入名为 self.websites 的属性中

db.collection("websites")
    .addSnapshotListener { (querySnapshot, err) in
      if let err = err {
      print("Error getting documents: \(err)")
     } else {
     guard let documents = querySnapshot?.documents else {
     print("no documents")
     return
    }
  self.websites = documents
       .flatMap { document -> Website in
  return try! document.data(as: Website.self)
      }
   }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM