js-data
js-data copied to clipboard
Add support for belongsToMany (many-to-many, hasManyThrough, pivot tables)
I really like this idea. It would be interesting to see how we could handle routing with something like this
+1
I'm currently working on the model definition, and we are using custom URLs for some of our not-so-RESTful endpoints by decorating the methods with a custom { endpoint : '/related/{{id}}/resource' }
method, in which the related resource is sometimes done via a many-to-many relationship. By keeping the URLs dynamic (meaning, it needs to be declared explicitly) you could potentially support this case and more complex cases, like nested relationship (we are using bookshelfjs capabilities to do something like Resource.get(someId, { include : ['related', 'related.children', 'related.children.grandchildren'] })
which our API endpoint supports.
If I can decouple this from our implementation I'll clean up the code to start up the discussion
That stuff already works for all adapters but the http adapter (because I have no control over what your REST api). Each of the other adapters have a with
option that will cause find
and findAll
to also retrieve relations, nested in the payload.
I really would like this feature. But it seems it is already there (but undocumented). Instead of using foreignKey
in a hasMany
context, you can use localKeys
. As far as a can see, this does exactly the same then belongsTo
, but with a list of foreign objects.
Do I miss something?
There isn't native support for many-to-many. Right now you have to use multiple hasMany and belongsTo relationships to make it work.
I am not sure, if I use the term many-to-many correctly. I have a user model and a motion model. Each motion can have supporters and each user can support more then one motion (that is what I call many-to-many).
This works great with js-data. I am only using hasMany: https://github.com/OpenSlides/OpenSlides/blob/master/openslides/motions/static/js/motions/motions.js#L55
With this code I can access motion.supporters and get a list of user objects.
I'm not completely sure that anything needs to be added to JSData for this. See http://stackoverflow.com/questions/33397943/many-to-many-relational-support-in-jsdata/33405764#33405764
Like I said before, you support it already. It would be nice if you added to your documentation, that hasMany
can be used without foreignKey
but with localKeys
instead.
https://github.com/js-data/js-data/blob/1d4882bc1059ee0504d88976656d7bf3013bfd00/src/utils.js#L656
Please add your suggestions to the docs by clicking the "Suggest Edits" button.