I create backbone collection from server JSON. Data is from mongo so each item has same objects and backbone remove this duplicates. It's unwanted behavior for me so, I can't find solution to keep this instances. After fetch my items has only 'section1' in secound object (id:2). I need the same section also in first object. For example my server response is:
items: [{
id:1,
sections: [{
id: 1.//this object is removed
name: 'section1'
}]
}, {
id: 2,
sections: [{
id:1.
name: 'section1'
}]
}]
My section model is just:
Section = Backbone.RelationalModel.extend({
});
and Item model:
Item = Backbone.RelationalModel.extend({
relations: [
{
'type': 'HasMany',
'key': 'sections',
'relatedModel': 'Section',
'includeInJSON': 'id',
'reverseRelation': {
'key': 'item',
'includeInJSON': 'id'
}
}
]
});
If I recall correctly, this plugin doesn't support many-to-many. So, what's happening is that it is attaching Section 1
to the first Item
, then attaching it to the second and removing it from the first.
In fact, from the docs:
Backbone.HasMany
Defines a HasMany relation. When defining a reverseRelation, the type will be HasOne.
Your options:
SectionItem
model that HasOne
Section
and HasOne
Item
. Someone posted a fiddle with this sort of setup http://jsfiddle.net/mmacaula/XaESG/2/Section
model key that would make each one unique. This is not a good way to achieve what you are trying to do, though.Here is a pretty good reference answer: Implementing a Many-to-Many relationship with Backbone-Relational