Function
belongsTo (modelName, options) Ember.computed public
Defined in ../model/addon/-private/belongs-to.js:13
- modelName
- String
- (optional) type of the relationship
- options
- Object
- (optional) a hash of options
- returns
- Ember.computed
- relationship
belongsTo
is used to define One-To-One and One-To-Many
relationships on a Model.
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. The default is true.inverse
: A string used to identify the inverse property on a related model in a One-To-Many relationship. See Explicit Inversespolymorphic
A boolean value to mark the relationship as polymorphic
One-To-One
To declare a one-to-one relationship between two models, use
belongsTo
:
app/models/user.js | |
1 2 3 4 5 |
import Model, { belongsTo } from '@ember-data/model'; export default Model.extend({ profile: belongsTo('profile') }); |
app/models/profile.js | |
1 2 3 4 5 |
import Model, { belongsTo } from '@ember-data/model'; export default Model.extend({ user: belongsTo('user') }); |
One-To-Many
To declare a one-to-many relationship between two models, use
belongsTo
in combination with hasMany
, like this:
app/models/post.js | |
1 2 3 4 5 |
import Model, { hasMany } from '@ember-data/model'; export default Model.extend({ comments: hasMany('comment') }); |
app/models/comment.js | |
1 2 3 4 5 |
import Model, { belongsTo } from '@ember-data/model'; export default Model.extend({ post: 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 | |
1 2 3 4 5 |
import Model, { belongsTo } from '@ember-data/model'; export default Model.extend({ post: belongsTo() }); |
will lookup for a Post type.
Sync relationships
Ember Data resolves sync relationships with the related resources available in its local store, hence it is expected these resources to be loaded before or along-side the primary resource.
app/models/comment.js | |
1 2 3 4 5 6 7 |
import Model, { belongsTo } from '@ember-data/model'; export default Model.extend({ post: belongsTo('post', { async: false }) }); |
In contrast to async relationship, accessing a sync relationship will always return the record (Model instance) for the existing local resource, or null. But it will error on access when a related resource is known to exist and it has not been loaded.
1 |
let post = comment.get('post'); |