Reputation: 7158
im trying to figure out if spine.js does support many to many relationships between models or if im on the better path implementing something myself by storing the related models id in an array on both sides.
examples in the documentation show pretty simple examples with a one to many situation only and even there im not getting smarter and to me it looks like the spine relation implementation is really limited. i still don't get how i could for example add existing instances to a relation rather than creating new ones.
the simplest example for what i need to do is the a typical blog with tags. Every Post can have many Tags and every Tag can have many Posts associated. When i create a Post i want to add new and/or existing Tags to the Post. and i need to be able to get all Posts related to a specific tag.
is there anybody able to bring me to the right path?
Upvotes: 0
Views: 406
Reputation: 285
mirror your xxx_yyy_ship model to Spine.Model
xxx.coffee include hasMany xxx_yyy_ship
yyy.coffee include hasMany xxx_yyy_ship
xxx::all_yyy -> ship.yyy for ship in @xxx_yyy_ship()
yyy::all_xxx -> ship.xxx for ship in @xxx_yyy_ship()
use hasMany and a middle ship model to simulate many to many relationship.
Upvotes: 0
Reputation: 11
I'm afraid I can't help you with the many-to-many relationship as I'm trying to solve the same problem at the moment, but as far as one-to-many for existing instances goes, you can add a foreign key as an optional parameter in the hasMany, hasOne and belongsTo functions (it defaults to '{className}_id'). The examples are slightly misleading as they imply that you have to explicitly add items to the collections, but in fact, the relationship is defined by the foreign key
class Parent extends Spine.Model
@configure 'Parent', 'id'
@hasMany 'children', 'Child', 'parent_id'
class Child extends Spine.Model
@configure 'Child', 'id', 'parent_id'
@belongsTo 'parent', 'Parent', 'parent_id'
parent = new Parent
child1 = new Child(parent_id: parent.id)
child2 = new Child(parent_id: parent.id)
@log parent.children().all() #[child1, child2]
@log child1.parent() is child2.parent() #true
as far as I can see, new Child(parent_id: parent.id)
and parent.children().create()
amount to the same thing, but I'm pretty new to SpineJS so I could easily be wrong...
I think there have been a couple of pull requests for many-to-many relationships, but Alex MacCaw has rejected them so far (I believe he's not a fan of the idea of relationships in general and is thinking of removing them from spine)
Upvotes: 1