我知道在SQL中,要将两个不同的对象相互关联,一个对象在一个表中使用主键,另一个表中使用外键。因为FirebaseDatabase使用JSON/NoSQL这是不可能的。如果我有两个对象,分别是UserPostEntity和PostEntity,那么一旦用户发出post/comment,我将如何将UserPostEntity与PostEntity关联起来,PostEntity将如何使用用户发出的post/comment自动更新?
用户实体对象:
import Foundation
class UserEntity{
var userID: String
var postedComment: String
var postDate: String
var postID: PostEntity
init(userID: String, postedComment: String, postDate: String, postID: PostEntity){
self.userID = userID
self.postedComment = postedComment
self.postDate = postDate
self.postID = postID
}
}
PostEntity对象:
import Foundation
class PostEntity{
var userID: String
var postID: String
var postedComment: String
var postDate: String
init(userID: String, postID: String, postedComment: String, postDate: String){
self.userID = userID
self.postID = postID
self.postedComment = postedComment
self.postDate = postDate
}
}
最佳答案
如果你能在Firebase中构建你的数据会更好。以下链接提供了在Firebase中构造数据的良好直觉:
https://firebase.googleblog.com/2013/04/denormalizing-your-data-is-normal.html
https://www.firebase.com/docs/web/guide/structuring-data.html
您可以定义user
表和posts
如下:
user{
"u1" {
userName : "abc",
posts {
p1 : true,
p2 : true
}
},
"u2" {
userName : "def",
posts {
p3 : true,
p4 : true
}
}
}
post{
"p1"{
userId : "u1",
postComment : "hello ios",
postDate : "1467570919"
},
"p2"{
userId : "u1",
postComment : "ios",
postDate : "1467570920"
},
"p3"{
userId : "u2",
postComment : "hello ios",
postDate : "1467570921"
},
"p4"{
userId : "u2",
postComment : "hello ios",
postDate : "1467570922"
}
}
也可以按如下方式创建实体:
class UserEntity{
var userID: String
var userName : String
var posts: Dictionary<String, Bool>?
var ref : FIRDatabaseReference?
init(userID: String, userName: String, posts: Dictionary<String, Bool>?){
self.userID = userID
self.userName = userName
self.posts = posts
self.ref = nil
}
}
class PostEntity{
var pId: String
var uId: String
var postedComment: String
var postDate: NSTimeInterval
var ref : FIRDatabaseReference?
init(pId: String, uId: String, postedComment: String, postDate: NSTimeInterval){
self.pId= pId
self.uId = uId
self.postedComment = postedComment
self.postDate = postDate
self.ref = nil
}
}
此外,您还需要按照post中的回答来构造
UserEntity
和PostEntity
实体。当用户添加新的post
posts
时,必须将user
表的p5 :true
属性更新为p5
。