Ember Data: Why hasMany and belongsTo

柔情痞子 提交于 2019-12-22 13:53:18

问题


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:


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.)



来源:https://stackoverflow.com/questions/25137401/ember-data-why-hasmany-and-belongsto

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!