通过hasMany连接进行过滤

时间:2015-07-03 18:16:43

标签: ember.js ember-data

我有一个route和一个destination模型,我想创建一个filteredRoutes计算属性,该属性只包含routesdestination.nameselectedDestination。我无法弄清楚最后一块拼图。我该如何过滤?

controller.js

filteredRoutes: Ember.computed('model.routes', 'selectedDestination', function() {
    var selectedDestination = this.get('selectedDestination');
    var routes = this.get('model.routes');

    if(selectedDestination) {
      routes = routes.filter(function(route) {
      // ????
      });
    }
  }),

应用/目的/ model.js

import DS from 'ember-data';

export default DS.Model.extend({
  name: DS.attr('string')
});

应用/路线/ model.js

import DS from 'ember-data';

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

1 个答案:

答案 0 :(得分:1)

按照您的建议使用filter,过滤条件是至少有一个名称等于所选目的地的目的地。

filteredRoutes: Ember.computed(
  'model.routes.@each.destinations.@each.name', 
  'selectedDestination', 

  function() {
    var selectedDestination = this.get('selectedDestination');

    return this.get('model.routes') . filter(
        route =>
          route.get('destinations') . find(
            destination =>
              destination.get('name') === selectedDestination
          )
    );
  }
)

英文:

  

查找至少有一个目的地的路线,其名称与所选目的地相同。