DS#belongsTo()

belongsTo (modelName, options) Ember.computed

Defined in addon/-private/system/relationships/belongs-to.js:5

DS.belongsTo is used to define One-To-One and One-To-Many relationships on a DS.Model.

DS.belongsTo takes an optional hash as a second parameter, currently supported options are:

  • async: A boolean value used to explicitly declare this to be an async relationship.
  • inverse: A string used to identify the inverse property on a related model in a One-To-Many relationship. See Explicit Inverses

One-To-One

To declare a one-to-one relationship between two models, use DS.belongsTo:

app/models/user.js
import DS from 'ember-data';

export default DS.Model.extend({
  profile: DS.belongsTo('profile')
});
app/models/profile.js
import DS from 'ember-data';

export default DS.Model.extend({
  user: DS.belongsTo('user')
});

One-To-Many

To declare a one-to-many relationship between two models, use DS.belongsTo in combination with DS.hasMany, like this:

app/models/post.js
import DS from 'ember-data';

export default DS.Model.extend({
  comments: DS.hasMany('comment')
});
app/models/comment.js
import DS from 'ember-data';

export default DS.Model.extend({
  post: DS.belongsTo('post')
});

You can avoid passing a string as the first parameter. In that case Ember Data will infer the type from the key name.

app/models/comment.js
import DS from 'ember-data';

export default DS.Model.extend({
  post: DS.belongsTo()
});

will lookup for a Post type.

Parameters:

modelName String
(optional) type of the relationship
options Object
(optional) a hash of options

Returns:

Ember.computed
relationship
doc_EmberJs
2016-11-30 16:49:20
Comments
Leave a Comment

Please login to continue.