在 Firebase Android 中是否有一种方法可以在范围内获取数据?

huangapple go评论59阅读模式
英文:

Is there a way in firebase android to fetch data within a range?

问题

我在 Firebase 实时数据库中有一个数据库。我的数据库看起来像这样:

我想要在一个日期范围内提取数据。也就是说,如果用户选择 2020 年 09 月 03 日作为开始日期,2020 年 09 月 05 日作为结束日期,我想要显示所有 TotalTax 字段的值(在这种情况下是 3 个值:500、500 和 100)。我应该如何实现这个目标呢?
希望你能理解我的意思:)。

英文:

I have a database in firebase realtime database.My DB look like this :

在 Firebase Android 中是否有一种方法可以在范围内获取数据?

I want to fetch data within a date range. That is if user select 03-09-2020 as start date and 05-09-2020 as end date,what i want is to display all values of TotalTax field (in this case 3 values 500,500 and 100).
How can i achieve this?
Hope you understand me :).

答案1

得分: 2

你的日期格式不允许获取一系列日期,因为这个范围不是连续的。假设你想要检索九月前三天的节点,在你当前的格式中,看起来像这样:

/// 这种方法无效
ref.orderByChild("Date").startAt("01-09-2020").endAt("03-09-2020")

但这不会起作用,因为这些值没有按字典顺序排序。

为了允许在一系列日期范围内检索节点,请使用一个按照时间顺序排列的字典顺序的格式存储这些值。例如:"2020-09-05" 表示 9 月 5 日。

有了这种日期格式,你可以使用以下查询日期范围的代码:

ref.orderByChild("Date").startAt("2020-09-01").endAt("2020-09-03")
英文:

Your date format does not allow fetching a range of dates, since the range is not sequential. Say you'd want to retrieve the nodes for the first three days of September, in your current format that'd look like this:

/// THIS DOES NOT WORK
ref.orderByChild("Date").startAt("01-09-2020").endAt("03-09-2020")

But this won't work because the values are not lexicographically sorted.

To allow retrieving the nodes on a range of dates, store those values in a format where the lexicographical order is the same as the chronological order. So: "2020-09-05" for September 5th.

With that date format, you can then query for the date range with:

ref.orderByChild("Date").startAt("2020-09-01").endAt("2020-09-03")

huangapple
  • 本文由 发表于 2020年9月5日 20:05:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/63753701.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定