Ember数据:为什么有很多和属于 [英] Ember Data: Why hasMany and belongsTo

查看:97
本文介绍了Ember数据:为什么有很多和属于的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么要在两个相关的数据集中定义hasMany belongsTo?它似乎是多余的,因为所有必需的信息都已经在其中一个阵列中,很难保持同步。

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.

它也不反映sql数据库中的表在一对多关系中,一个表中只有一个外键。

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.

推荐答案

因为关系可以走一个两种方式。在您的SQL示例中,一个表中的外键仅对该表进行约束,而不是外键所属的表。在某种意义上,这只是一种单向关系。第一个表中的行必须链接到第二个表的行,但反之亦然。如果你想模拟这种行为,你应该使用一个 null inverse,如下所示:

Because relationships can go one or two ways. In your SQL example, a foreign key in one table only paces 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
});

具有双向关系是不同的。要扩展SQL比较,那就想要有两个外键,每个表中有一个。表A的行必须指向表B的行,表B的行必须指向表A的行。

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.

但是SQL真的是这里比较糟糕。如果担心这种不匹配,您将让数据存储实现泄漏到数据模型中。相反,您应该将Ember-Data模型视为图形。具体来说,有向图。一旦了解了有针对性的图形,以及如何遍历它们,您将了解为什么大多数人使用双向关系。 (虽然,如上所述,你不必。)

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

这篇关于Ember数据:为什么有很多和属于的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆