firebase排序逆序

时间:2017-04-06 10:39:50

标签: sorting firebase firebase-realtime-database

enter image description here

var playersRef = firebase.database().ref("team_mapping/");


playersRef.orderByChild("score").limitToFirst(7).on("child_added", function(data) {
}

使用此查询,我可以按升序对其进行排序。但是,我想按降序排序。任何身体都可以通过某种方式建议我这样做。任何帮助将不胜感激。

先谢谢!!

3 个答案:

答案 0 :(得分:2)

在数组上使用reverse(),假设您将值存储到数组items []然后执行this.items.reverse()

ref.subscribe(snapshots => {
       this.items = [];
      snapshots.forEach(snapshot => {

        this.items.push(snapshot);

      });
      **this.items.reverse();**
    },

答案 1 :(得分:1)

您可以限制为最后7,这将为您提供最高分数,因为查询是按升序排列的。然后你所要做的就是扭转你得到的最后7个降序。

var playersRef = firebase.database().ref("team_mapping/");
var playersData = [];
var pageCursor;

playersRef.orderByChild("score").limitToLast(7).on("child_added", function(data) {
    playersData = [data] + playersData;
}

<强>更新

以下是您可以按分数进行分页的示例。

const query = firebase.database().ref("team_mappings").orderByChild('score');

var snapshots = [];

function reversedChildren(snapshot) {
    var children = [];
    snapshot.forEach(function (child) { children.unshift(child); });
    return children;
}

function addPlayerToLeaderBoard(snapshot) {
    var key = snapshot.key;
    var place = snapshots.indexOf(snapshot) + 1;
    var score = snapshot.child('score').val();
    $('#leaderboard').append(`<li><b>${key}: ${score}</li>`);
}

function parsePage(snapshot) {
    var children = reversedChildren(snapshot);
    children.forEach(function (child) {
        players.push(child);
        addPlayerToLeaderBoard(child);
    });
    pageCursor = children[children.length - 1];
}

function reloadPlayers() {
    players = [];
    pageCursor = null;
    query.limitToLast(5).once('value').then(parsePage);
}

function loadMorePlayers() {
    query.endAt(pageCursor).limitToLast(5).once('value').then(parsePage);
}

reloadPlayers();

$('#reload').on('click', reloadPlayers);
$('#load_more').on('click', loadMorePlayers);

答案 2 :(得分:0)

不幸的是,这还没有捷径。但是,如果您将Listview或Recyclerview用作UI,则可以通过反转UI,反转Listview或Recyclerview来简单地解决此问题

对于Recyclerview,您可以按以下步骤进行反向操作:

LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(layoutManager)

对于Listview:

listView.setStackFromBottom(true);