简体   繁体   English

Firebase:按孩子数排序的查询

[英]Firebase: Query ordered by children count

In my firebase database, I have a child called Hashtag. 在我的Firebase数据库中,我有一个名为Hashtag的孩子。 That child contains names of hashtags, and that child contains the posts that are apart of those hashtags. 该子对象包含主题标签名称,而该子对象包含这些主题标签之外的帖子。

For example 例如

Hashtags
    L #firstHashtag
            L post1: true
            L post2: true
            L post3: true
    L #secondHashtag
            L post4: true
            L post5: true
            L post6: true
            L post7: true
            L post8: true
    L #thirdHashtag
            L post9: true

That is how my database looks. 那就是我的数据库的样子。

First hashtag has three posts. 第一个主题标签有三个帖子。

Second hashtag has five posts. 第二个主题标签有五个帖子。

Third hashtag has one post. 第三个主题标签有一个帖子。

This is my hashtag reference 这是我的标签参考

var HASHTAG_REFERENCE = Database.database().reference().child("Hashtags")

My goal is to query the hashtags in order of most popular. 我的目标是按照最受欢迎的顺序查询主题标签。 A hashtag with the most posts is the most popular hashtag. 帖子数最多的主题标签是最受欢迎的主题标签。 A hashtag with the least posts is the least popular hashtag. 帖子最少的主题标签是最受欢迎的主题标签。

So the most popular hashtag would be secondHashtag, and I want to receive the name of that hashtag first. 因此,最受欢迎的标签是secondHashtag,我想首先接收该标签的名称。 The least popular hashtag is thirdHashtag, and i want to receive the name of that hashtag last 最受欢迎的主题标签为thirdHashtag,我希望最后接收该主题标签的名称。

How can i query my database so it can order the children in terms of their post count? 我如何查询我的数据库,以便可以按照孩子们的职位数对其排序?

There's no native query that lets you order by number of children. 没有本机查询可让您按孩子数进行排序。 Instead, you'll have to maintain a count of the posts, stored in another child, and order the hashtags by the value of that. 取而代之的是,您必须维护存储在另一个子项中的帖子数,并按照该值对主题标签进行排序。

You have two choices for this. 您有两种选择。 You can maintain the count on the client whenever it adds a post to a hashtag. 只要将帖子添加到主题标签,就可以维护客户端的计数。 Or, write a Cloud Function that automatically keeps the count up to date whenever something changes. 或者,编写一个Cloud Function,以便在发生任何更改时自动使计数保持最新。 In either case, be sure to use a transaction to avoid conflict from multiple writers. 无论哪种情况,请确保使用事务以避免来自多个编写器的冲突。

Also bear in mind that, because you want the reverse order of the count of posts, you'll have to store a value that naturally orders from most posts to least posts. 还请记住,因为您想要相反的帖子数量顺序,所以您必须存储一个值,该值自然可以从大多数帖子到最少帖子。 You could store a negative count to make sure the most popular posts (which therefore have the smallest values) are ordered ahead of the least popular (which have the largest values). 您可以存储一个负数,以确保最受欢迎的帖子(因此具有最小的值)被排列在最不受欢迎的帖子(具有最大的值)之前。

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

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