简体   繁体   中英

Swift + Firestore: How to fetch related objects

I have this model in 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":

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.

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:

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. In the scenario below, I am getting all the documents in the Firestore collection websites and putting them into a property called 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)
      }
   }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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