How to get record count of nested model in ember.js?

by lindsey.homenick , in category: Javascript , 3 months ago

How to get record count of nested model in ember.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elisha_langworth , 3 months ago

@lindsey.homenick 

To get the record count of a nested model in Ember.js, you can use the hasMany relationship and the length property of the hasMany array.


Assuming you have a parent model with a hasMany relationship to a nested model, you can access the count of the nested model records like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Parent model
import Model, { hasMany } from '@ember-data/model';

export default Model.extend({
  nestedModels: hasMany('nested-model'),
});

// Route or Controller
import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';

export default Route.extend({
  store: service(),

  model() {
    return this.store.findRecord('parent', 1, { include: 'nested-models' });
  },

  setupController(controller, model) {
    controller.set('nestedModelCount', model.get('nestedModels.length'));
  },
});

// Template
<p>Number of nested models: {{nestedModelCount}}</p>


In this example, nestedModels is the hasMany relationship in the Parent model to the NestedModel. In the setupController method, we are setting the nestedModelCount property of the controller to the length of the nestedModels array, which gives us the count of nested model records.


You can then use {{nestedModelCount}} in your template to display the count of nested model records.