Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 39 ยท Ember Data and Models

Relationships: belongsTo and hasMany

Link Ember Data models with belongsTo and hasMany, understand async versus sync relationships, inverses and loading related records, with a runnable stand-in that keeps both sides in step.

Data rarely stands alone. A blog post has an author and many comments; an order has a customer and many line items. Relationships declare these links between models. Once declared, you navigate them like properties (post.author.name), and Ember Data keeps both sides consistent: add a comment to a post and the comment's post points back at it.

Real versus stand-in. Model and template code is real Ember Data, read-only here. The runnable blocks implement a small version of the "two-sided link" idea in plain JavaScript.

Declaring relationships

JavaScript
// app/models/post.js
import Model, { attr, belongsTo, hasMany } from '@ember-data/model';

export default class PostModel extends Model {
  @attr('string') title;

  @belongsTo('author', { async: false, inverse: 'posts' }) author;
  @hasMany('comment', { async: true, inverse: 'post' }) comments;
}
JavaScript
// app/models/author.js
export default class AuthorModel extends Model {
  @attr('string') name;
  @hasMany('post', { async: true, inverse: 'author' }) posts;
}
JavaScript
// app/models/comment.js
export default class CommentModel extends Model {
  @attr('string') text;
  @belongsTo('post', { async: false, inverse: 'comments' }) post;
}
  • belongsTo: this record points to one other record (a post belongs to an author). It is the "many" side of a one-to-many.
  • hasMany: this record holds a list of other records.
  • The first argument is the related model name.
  • inverse names the relationship on the other model that mirrors this one. Current Ember Data wants it stated explicitly (use inverse: null if there is no mirror).
  • async is also required: true or false, explained next.

Relationship kinds in practice: one-to-many (author and posts), many-to-many (posts and tags: hasMany on both sides), one-to-one (user and profile: belongsTo on both sides) and one-way (a post's featuredComment with inverse: null).

Async versus sync relationships

The server may not have sent the related records yet. With async: true the relationship returns a promise-like proxy that loads the related record(s) on demand:

JavaScript
<template>
  <h2>{{@model.title}}</h2>
  {{#each @model.comments as |comment|}}
    <p>{{comment.text}}</p>
  {{/each}}
</template>

The template can render this directly. When the comments are not yet loaded the list is empty, then fills in as they arrive. In JavaScript you await it:

JavaScript
const comments = await post.comments;
const author = await post.author;

With async: false the relationship is a plain reference to a record that must already be loaded. If it is not, Ember Data throws an error. Sync relationships are simpler to use (no awaiting) and are the best choice when you load the related data together with the parent, for example with include (see Querying and Caching).

async: true async: false
Value proxy / promise record or list
Missing data fetched on demand error
Needs await in JS yes no
Good for large or optional related data data always loaded with the parent

In JSON:API, relationships appear next to attributes. Only the type and id are required; a links entry can tell Ember Data where to fetch the rest:

JSON
{
  "data": {
    "type": "posts",
    "id": "1",
    "attributes": { "title": "Hello" },
    "relationships": {
      "author": { "data": { "type": "authors", "id": "7" } },
      "comments": { "links": { "related": "/posts/1/comments" } }
    }
  }
}

Author 7 is listed by id; when the template asks for post.author.name, the store looks it up in its cache or requests /authors/7. The comments come from the related link only when someone reads post.comments. That is how an async: true relationship avoids fetching everything up front.

Changing relationships

Assign records, and the other side updates automatically:

JavaScript
const post = this.store.createRecord('post', { title: 'New' });
post.author = grace;           // belongsTo: assign a record
grace.posts.push(post);        // hasMany: use array methods (it is a managed array)
post.comments.push(comment);   // comment.post now points to post

Because of the inverse, post.author = grace also adds post to grace.posts, and vice versa. To remove a link, set a belongsTo to null or call .splice / .pop on a hasMany.

JS Stand-in: both sides stay in step

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Three common ways to get the related records:

  1. Lazy (async relationships): read post.comments and the store fetches on demand.
  2. Included: ask the server to send them with the parent: store.findRecord('post', 1, { include: 'author,comments' }). One request, and sync relationships work immediately. Nested: include: 'comments.author'.
  3. In the route: load each in model() with RSVP.hash or Promise.all:
JavaScript
async model({ post_id }) {
  const post = await this.store.findRecord('post', post_id, { include: 'comments' });
  return { post, relatedPosts: await this.store.query('post', { filter: { related: post_id } }) };
}

Pick lazy loading for data that is rarely seen and include for data you always show.

JS Stand-in: lazy versus included loading

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Polymorphic relationships (brief)

If a relationship can point to different model types (a comment on a post or on a photo), mark it polymorphic: true and give the other side the same option. The server's type field decides which model is built. Use it sparingly; most apps never need it.

Common mistakes

  • Missing async or inverse. Recent versions require both; the error message tells you.
  • Treating an async relationship as a plain array in JavaScript. Use await post.comments, or read it in a template.
  • A sync relationship to unloaded data. Add include, or switch to async: true.
  • Replacing a hasMany list. Mutate it with push, splice or pop (it is a managed array); the inverse stays in sync.
  • An inverse that does not match. If inverse: 'author' points to a field that is not there, relationships silently stop mirroring.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A comment belongs to one post, and a post has many comments. Which declarations are right?

    The model holding the single reference uses belongsTo; the model holding the list uses hasMany.
  2. 2. What happens when an async false relationship points to a record that is not loaded?

    Sync relationships require the data to be present, for example loaded with include.
  3. 3. What does the inverse option do?

    With inverses, setting post.author also updates author.posts, and vice versa.
  4. 4. How do you get a post and its comments in one request?

    The include option asks a JSON:API server to return the related records together with the primary record.

Summary

  • @belongsTo points to one record, @hasMany holds a list; both need async and inverse options.
  • Async relationships load on demand and need await in JavaScript; sync ones need the data already loaded.
  • Inverses keep both sides consistent when you assign or push.
  • Use include to load related records in one request.
  • Polymorphic relationships exist but are rarely needed.

Next: Creating, Updating and Deleting Records