[英]In Ember data, what is the best way to form association between two objects?
Let's say some DS.Model class Leaf
belongsTo class Tree
, and one Tree
hasMany leaves
, ie: 假设某些DS.Model类
Leaf
属于To类Tree
,并且其中一个Tree
hasMany leaves
,即:
App.Leaf = DS.Model.extend({
tree: DS.belongsTo('App.Tree'),
});
App.Tree = DS.Model.extend({
leaves: DS.hasMany('App.Leaf'),
})
So far I'm manually manipulating Tree
's leaves field: 到目前为止,我正在手动操作
Tree
的leaves字段:
tree = App.store.create( App.Tree )
leaf = App.store.create( App.Leaf )
tree.get('leaves').pushObject( leaf )
App.store.commit()
Now this appears to work but then things get weird: 现在,这似乎可行,但是事情变得奇怪了:
when I check leaf's tree field, I see a App.Tree instance is in there and the id matchs that of tree: 当我检查leaf的tree字段时,我看到其中有一个App.Tree实例,并且id与tree匹配:
leaf.get('tree').get('id') // outputs 1
tree.get('id') // outputs 1
So far ok. 到目前为止,还可以。 Now I check tree's leaves field, which I presume is an Ember mutable-array, and I see this:
现在,我检查树的leaves字段,我假设它是一个Ember可变数组,我看到了:
branch.get('leaves').content // outputs [ 2 ]
leaf.get('id') // outputs 1
So I presume the leaves mutable-array is storing an array of leaf ids, except its id does not match that of the leaf instance. 因此,我假设叶子的可变数组存储的是叶子ID的数组,但其ID与叶子实例的ID不匹配。
Note when the leaf's id is 2, it's stored in the branch.leaves.content field as 4, if leaf id is 3, the stored id is 6, etc. 请注意,当叶子的ID为2时,将其存储在branch.leaves.content字段中,值为4,如果叶子的ID为3,则存储的ID为6,依此类推。
Everything is working properly in your example, accessing the content variable branch.get('leaves')
record array returns an array of the clientId
's of the objects. 在您的示例中,一切工作正常,访问内容变量
branch.get('leaves')
记录数组将返回对象的clientId
的数组。
However that is the exception as accessing properties any other way will transparently accesses the objects themselves. 但是,这是例外,因为以任何其他方式访问属性都将透明地访问对象本身。
In your case if you want ID's use branch.get('leaves').mapProperty('id')
在您的情况下,如果要使用ID,请使用
branch.get('leaves').mapProperty('id')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.