Function
belongsTo (modelName, options) Ember.computed public
Defined in ../model/addon/-private/belongs-to.js:11
- 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 ' -data/model'; export default class UserModel extends Model { ('profile') profile; } |
app/models/profile.js | |
1 2 3 4 5 |
import Model, { belongsTo } from ' -data/model'; export default class ProfileModel extends Model { ('user') 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 ' -data/model'; export default class PostModel extends Model { ('comment') comments; } |
app/models/comment.js | |
1 2 3 4 5 |
import Model, { belongsTo } from ' -data/model'; export default class CommentModel extends Model { ('post') 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 ' -data/model'; export default class CommentModel extends Model { post; } |
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 8 |
import Model, { belongsTo } from ' -data/model'; export default class CommentModel extends Model { ('post', { async: false }) post; } |
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'); |