2
votes

I'm wondering why I have to define hasMany and belongsTo in two related data sets? It seems redundant as all necessary information is in one of the arrays already and it is difficult to keep both synchronized.

It also doesn't reflect the tables in an sql database where there is only one foreign key in one table in an one-to-many relationship.

1

1 Answers

3
votes

Because relationships can go one or two ways. In your SQL example, a foreign key in one table only places a restraint on that table, NOT the table to which the foreign key belongs. In a sense, this is only a one way relationship. Rows from the first table must be linked to rows of the second, but not vice-versa. If you want to emulate that behavior, you should use a null inverse, like so:

App.User = DS.Model.extend({
    posts: DS.hasMany('post', { inverse: null });
});

App.Post = DS.Model.extend({
    // No inverse relationship required
});

Having a two way relationship is different though. To stretch your SQL comparison, that would like having two foreign keys, one in each table. Rows of table A must point to rows of table B and rows of table B must point to rows of table A.

But SQL really is a bad comparison here. You're letting your data store implementation leak through to your data model if you're worried about that mismatch. Instead, you should think about Ember-Data models as graphs. Specifically, directed graphs. Once you understand directed graphs, and how to traverse them, you'll understand why most people use two-sided relationships. (Although, as I showed you above, you don't have to.)