我正在尝试在FIRDatabaseQuery对象上进行内连接。
下面是数据库结构。我有一些链接到评论后的帖子。我试图获取特定用户添加评论的所有帖子:
{
"posts" : {
"-KIycKhZU55dmKnHbbxv" : {
"author" : "John Doe",
"body" : "This is a post test",
"title" : "test",
"uid" : "SHaH36BLwgPvwgi9cDmRnsnONFB2"
},
"-KIyg_ks1O5QL4_4dfq_" : {
"author" : "Jane Doe",
"body" : "This is a post test",
"title" : "test2",
"uid" : "x5leSBGArnd10JilD9YDyNBNfZ03"
},...
}
"post-comments" : {
"-KIycKhZU55dmKnHbbxv" : {
"-KIycMyL0Vy1BHVdI4zc" : {
"author" : "toto",
"text" : "test",
"uid" : "SHaH36BLwgPvwgi9cDmRnsnONFB2"
},
"-KIyg_ks1O5QL4_4dfq_" : {
"author" : "toto",
"text" : "test",
"uid" : "SHaH36BLwgPvwgi9cDmRnsnONFB2"
}
},...
}
在SQL中,这将被翻译成类似于:
的内部联接查询从帖子内部加入后评论中选择* post-comments上的评论,其中post-comments.uid =“user id”
有人知道如何在firebase中获得类似于内连接的东西吗?
非常感谢, 亚辛
答案 0 :(得分:4)
您可能需要考虑
"posts" : {
"-KIycKhZU55dmKnHbbxv" : {
"author" : "John Doe",
"body" : "This is a post test",
"title" : "test",
"uid" : "SHaH36BLwgPvwgi9cDmRnsnONFB2"
"commented_by"
"SHaH36BLwgPvwgi9cDmRnsnONFB2": true
然后你可以简单地查询
posts.child("commented_by/uid").queryEqualToValue(true)
或者,更改后评论以更好地匹配您要执行的查询:
"post-comments" : {
"-KIycMyL0Vy1BHVdI4zc" : {
"author" : "toto",
"post_data":
post_id: "-KIycKhZU55dmKnHbbxv",
post_title: "test"
"text" : "test",
"uid" : "SHaH36BLwgPvwgi9cDmRnsnONFB2"
},
这使查询成为一个快照,因为可以为uid查询post-comments节点,该uid返回他们评论过的帖子的所有post_id。它不会返回帖子本身,但是,您可能只是在寻找标题,以便您可以填充列表。用户点击它后点击它就可以检索实际数据。
答案 1 :(得分:3)
您需要使用嵌套的firebase调用。您可以找到javascript example in this question,但您的快速代码应如下所示:
ref.child("posts").observeEventType(.ChildAdded, withBlock: { (snapshot) in
if let postId = snapshot.key as! String {
let commentsRef = ref.child("post-comments")
commentsRef.child(postId).queryOrderedByChild("uid").queryEqualToValue(userId).observeSingleEventOfType(.Value, withBlock: { (snapshot) in
for child in snapshot.children.allObjects as [FDataSnapshot] {
print(child.value)
}
}) { (error) in
print(error.localizedDescription)
}
}
})