我知道在SQL中将2个不同的对象相互关联,会在1个表中使用主键,在另一个表中使用外键。由于FirebaseDatabase使用的JSON / NoSQL是不可能的。如果我有2个对象是UserPostEntity和PostEntity,那么一旦用户发布帖子/评论,我将如何将UserPostEntity与PostEntity相关联,以及如何使用用户发布的帖子/评论自动更新PostEntity?
UserEntity对象:
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
}
}
答案 0 :(得分:2)
如果您可以在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
实体。
当用户posts
添加新帖user
时,您必须将p5 :true
表的p5
属性更新为u1
。