API Docs for: 5.4.0-alpha.27+524e8e8a
Show:

HasManyReference Class

A HasManyReference is a low-level API that allows access and manipulation of a hasMany relationship.

It is especially useful when you're dealing with async relationships from @ember-data/model as it allows synchronous access to the relationship data if loaded, as well as APIs for loading, reloading the data or accessing available information without triggering a load.

It may also be useful when using sync relationships with @ember-data/model that need to be loaded/reloaded with more precise timing than marking the relationship as async and relying on autofetch would have allowed.

However,keep in mind that marking a relationship as async: false will introduce bugs into your application if the data is not always guaranteed to be available by the time the relationship is accessed. Ergo, it is recommended when using this approach to utilize links for unloaded relationship state instead of identifiers.

Reference APIs are entangled with the relationship's underlying state, thus any getters or cached properties that utilize these will properly invalidate if the relationship state changes.

References are "stable", meaning that multiple calls to retrieve the reference for a given relationship will always return the same HasManyReference.

Item Index

Properties

Methods

ids

() Array public

ids() returns an array of the record IDs in this relationship.

Example

import Model, { hasMany } from '@ember-data/model';

export default class PostModel extends Model {
  @hasMany('comment', { async: true, inverse: null }) comments;
}
let post = store.push({
  data: {
    type: 'post',
    id: 1,
    relationships: {
      comments: {
        data: [{ type: 'comment', id: 1 }]
      }
    }
  }
});

let commentsRef = post.hasMany('comments');

commentsRef.ids(); // ['1']

Returns:

Array:

The ids in this has-many relationship

load

(
  • options
)
Promise public

Loads the relationship if it is not already loaded. If the relationship is already loaded this method does not trigger a new load. This causes a request to the specified relationship link or reloads all items currently in the relationship.

Example

import Model, { hasMany } from '@ember-data/model';

export default class PostModel extends Model {
  @hasMany('comment', { async: true, inverse: null }) comments;
}
let post = store.push({
  data: {
    type: 'post',
    id: 1,
    relationships: {
      comments: {
        data: [{ type: 'comment', id: 1 }]
      }
    }
  }
});

let commentsRef = post.hasMany('comments');

commentsRef.load().then(function(comments) {
  //...
});

You may also pass in an options object whose properties will be fed forward. This enables you to pass adapterOptions into the request given to the adapter via the reference.

Example

commentsRef.load({ adapterOptions: { isPrivate: true } })
  .then(function(comments) {
    //...
  });
export default ApplicationAdapter.extend({
  findMany(store, type, id, snapshots) {
    // In the adapter you will have access to adapterOptions.
    let adapterOptions = snapshots[0].adapterOptions;
  }
});

Parameters:

  • options Object

    the options to pass in.

Returns:

Promise:

a promise that resolves with the ManyArray in this has-many relationship.

meta

() Object | Null public

The meta data for the has-many relationship.

Example

// models/blog.js
import Model, { hasMany } from '@ember-data/model';
export default Model.extend({
   users: hasMany('user', { async: true, inverse: null })
 });

let blog = store.push({
   data: {
     type: 'blog',
     id: 1,
     relationships: {
       users: {
         links: {
           related: {
             href: '/articles/1/authors'
           },
         },
         meta: {
           lastUpdated: 1458014400000
         }
       }
     }
   }
 });

let usersRef = blog.hasMany('user');

usersRef.meta() // { lastUpdated: 1458014400000 }

Returns:

Object | Null:

The meta information for the belongs-to relationship.

push

(
  • doc
  • [skipFetch]
)
Promise public

push can be used to update the data in the relationship and EmberData will treat the new data as the canonical value of this relationship on the backend. An empty array will signify the canonical value should be empty.

Example model

import Model, { hasMany } from '@ember-data/model';

export default class PostModel extends Model {
  @hasMany('comment', { async: true, inverse: null }) comments;
}

Setup some initial state, note we haven't loaded the comments yet:

const post = store.push({
  data: {
    type: 'post',
    id: '1',
    relationships: {
      comments: {
        data: [{ type: 'comment', id: '1' }]
      }
    }
  }
});

const commentsRef = post.hasMany('comments');
commentsRef.ids(); // ['1']

Update the state using push, note we can do this even without having loaded these comments yet by providing resource identifiers.

Both full resources and resource identifiers are supported.

await commentsRef.push({
 data: [
  { type: 'comment', id: '2' },
  { type: 'comment', id: '3' },
 ]
});

commentsRef.ids(); // ['2', '3']

For convenience, you can also pass in an array of resources or resource identifiers without wrapping them in the data property:

await commentsRef.push([
  { type: 'comment', id: '4' },
  { type: 'comment', id: '5' },
]);

commentsRef.ids(); // ['4', '5']

When using the data property, you may also include other resource data via included, as well as provide new links and meta to the relationship.

await commentsRef.push({
  links: {
    related: '/posts/1/comments'
  },
  meta: {
    total: 2
  },
  data: [
    { type: 'comment', id: '4' },
    { type: 'comment', id: '5' },
  ],
  included: [
    { type: 'other-thing', id: '1', attributes: { foo: 'bar' },
  ]
});

By default, the store will attempt to fetch any unloaded records before resolving the returned promise with the ManyArray.

Alternatively, pass true as the second argument to avoid fetching unloaded records and instead the promise will resolve with void without attempting to fetch. This is particularly useful if you want to update the state of the relationship without forcing the load of all of the associated records.

Parameters:

  • doc Array | Object

    a JSONAPI document object describing the new value of this relationship.

  • [skipFetch] Boolean optional

    if true, do not attempt to fetch unloaded records

Returns:

Promise:

reload

(
  • options
)
Promise public

Reloads this has-many relationship. This causes a request to the specified relationship link or reloads all items currently in the relationship.

Example

import Model, { hasMany } from '@ember-data/model';

export default class PostModel extends Model {
  @hasMany('comment', { async: true, inverse: null }) comments;
}
let post = store.push({
  data: {
    type: 'post',
    id: 1,
    relationships: {
      comments: {
        data: [{ type: 'comment', id: 1 }]
      }
    }
  }
});

let commentsRef = post.hasMany('comments');

commentsRef.reload().then(function(comments) {
  //...
});

You may also pass in an options object whose properties will be fed forward. This enables you to pass adapterOptions into the request given to the adapter via the reference. A full example can be found in the load method.

Example

commentsRef.reload({ adapterOptions: { isPrivate: true } })

Parameters:

  • options Object

    the options to pass in.

Returns:

Promise:

a promise that resolves with the ManyArray in this has-many relationship.

remoteType

() String public

This returns a string that represents how the reference will be looked up when it is loaded. If the relationship has a link it will use the "link" otherwise it defaults to "id".

Example

import Model, { hasMany } from '@ember-data/model';

export default class PostModel extends Model {
  @hasMany('comment', { async: true, inverse: null }) comments;
}
let post = store.push({
  data: {
    type: 'post',
    id: 1,
    relationships: {
      comments: {
        data: [{ type: 'comment', id: 1 }]
      }
    }
  }
});

let commentsRef = post.hasMany('comments');

// get the identifier of the reference
if (commentsRef.remoteType() === "ids") {
  let ids = commentsRef.ids();
} else if (commentsRef.remoteType() === "link") {
  let link = commentsRef.link();
}

Returns:

String:

The name of the remote type. This should either be link or ids

value

() ManyArray public

value() synchronously returns the current value of the has-many relationship. Unlike record.relationshipName, calling value() on a reference does not trigger a fetch if the async relationship is not yet loaded. If the relationship is not loaded it will always return null.

Example

import Model, { hasMany } from '@ember-data/model';

export default class PostModel extends Model {
  @hasMany('comment', { async: true, inverse: null }) comments;
}
let post = store.push({
  data: {
    type: 'post',
    id: 1,
    relationships: {
      comments: {
        data: [{ type: 'comment', id: 1 }]
      }
    }
  }
});

let commentsRef = post.hasMany('comments');

post.comments.then(function(comments) {
  commentsRef.value() === comments
})

Returns:

Properties

identifiers

StableRecordIdentifier[] public

An array of identifiers for the records that this reference refers to.

key

String public

The field name on the parent record for this has-many relationship.

type

String public

The type of resource this relationship will contain.