Firebase范围查询 [英] Firebase range query

查看:65
本文介绍了Firebase范围查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用AngularFire+Firebase并在firebase-database处有数据.

我正在尝试使用智能表格

我的问题是我不知道如何在不指定任何子对象的情况下进行范围查询,即从记录#25到35中获取记录

My problem is that I dont know how to range query without specifying any child i,e fetch records from record # 25 to 35

下面的查询给了我前5条记录

Below query gives me first 5 records

var queryFIrst = visitRef.startAt().limitToFirst(5);
$scope.Visits = $firebaseArray(queryFIrst);

现在我正尝试从5到6记录下5条记录,而我尝试了以下记录

now Im trying to get records next 5,from 6 to 10 and I tried below

var queryFIrst = visitRef.startAt().limitToFirst(5).endAt().limitToFirst(5);
$scope.Visits = $firebaseArray(queryFIrst);

但它给出了错误,指出startAtendAt不能与limit一起使用

but it giving error that startAt and endAt can't be used like this with limit

推荐答案

通常,分页并不适合Firebase的实时数据模型/API.您正在尝试对SQL SKIP运算符建模,该运算符不适用于Firebase数据库.

In general pagination is not a good fit for Firebase's realtime data model/API. You're trying to model a SQL SKIP operator, which won't work with the Firebase Database.

但是,如果要在Firebase中对分页进行建模,则应考虑使用锚点".

But if you want to model pagination in Firebase, you should think of having an "anchor point".

加载第一页后,该页上的最后一项将成为定位点.然后,当您想加载下一页时,您将创建一个从锚点开始并加载n + 1项的查询.

When you've loaded the first page, the last item on that page becomes the anchor point. When you then want to load the next page, you create a query that starts at the anchor point and load n+1 item.

使用伪代码(这是真正的JavaScript,我只是没有运行它):

In pseudo-code (it's real JavaScript, I just didn't run it):

var page1 = visitRef.orderByKey().limitToFirst(5);
var anchorKey;
page1.on('child_added', function(snapshot) {
  anchorKey = snapshot.key; // this will always be the last child_added we received
});

现在,当您要加载下一页项目时,您将创建一个从定位键开始的新查询:

Now when you want to load the next page of items, you create a new query that starts at the anchor key:

var page2 = visitRef.orderByKey().startAt(anchorKey).limitToFirst(6);

这里需要注意的几件事:

A few things to note here:

  • 您似乎正在使用Firebase 1.x SDK中的方法,例如空的startAt().虽然该代码可能仍然有效,但是我的代码片段使用了3.x SDK的语法/惯用语.
  • 对于第二页,您需要再加载一个项目,因为两个页面都加载了锚定项目.
  • 如果您希望能够分页,则在页面开始时还需要定位键.
  • You seem to be using an approach from the Firebase 1.x SDK, such as an empty startAt(). While that code may still work, my snippets use the syntax/idiom for the 3.x SDK.
  • For the second page you'll need to load one extra item, since the anchor item is loaded for both pages.
  • If you want to be able to paginate back, you'll also need the anchor key at the start of the page.

这篇关于Firebase范围查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆