Search code examples
javascriptember.jsemberfire

Is it possible to order the hasMany relative data in Ember with Emberfire?


I've two different models, with hasMany/belongsTo relationships between them. Ordering the request regular positions (like in this case name) by Emberfire it's easy. But I cannot figure it out how to do it with relationships
On the route's template we have Model1 in the route and loop through different positions on model 1. Inside, we loop through linked model2 positions, but they should be ordered by day
Model 1

export default DS.Model.extend({
  name : DS.attr('string'),
  model2 : DS.hasMany('model2', {async: true})
});

Model 2

export default DS.Model.extend({
  day : DS.attr('number'),
  model1 : DS.belongsTo('model1', { async: true })
});

Solution

  • When you access the async property you are merely accessing the entities associated with that relationship, not performing a search (so there is no way, at least without rolling your own solution, to filter these entities on the fetch).

    The easiest way to handle this would be to have a computed property on your controller / class which orders the child models by day.

    Another option (if you want Emberfire to handle the ordering for you) is to just not rely on lazy loading, and rather query for child models directly and order by the day field in that query.

    -- Edit for example --

    You'd want to watch changes to your selected model's model2 property as follows:

    sortedList: Ember.computed('selectedModel.model2.[]', function() {
        return this.get('selectedModel.model2').sortBy('day');
    }