Save model with hasMany
See original GitHub issueImagine a typical relationship between a User
model and a Course
model. A user can have many courses and a course can have many users. This is a normal many to many relationship. However, I also need some columns on the join table. Imagine that a discount associated with the user <-> course association.
I’m writing a web api, and I have an endpoint that accepts something like this JSON (POST /users/123
):
{
"firstName": "Miguel",
"lastName": "Andrade",
"courses": [
{
"course_id": 1,
"discount": 0.23
},
{
"course_id": 4,
"discount": 0.33
}
]
}
This is what the web app sends after the user submits a form where he/she can choose courses and their respective discounts.
The question is, what is the appropriate way to save this JSON in Bookshelf?
I don’t mind transforming this many-to-many in two one-to-many. I could create a Model called CourseSubscription
which could hold the relationships and the additional discount.
Either way, I’d like to know how to best tackle this problem.
Issue Analytics
- State:
- Created 8 years ago
- Comments:6 (3 by maintainers)
@miguelcobain See #831. Something like this, perhaps:
Could take
withRelated: true
to accept all. There’s a few things that need to happen before then though.@rhys-vdw Something came up that I think is somewhat related with this issue. So I thought to include it here for anyone that may need it.
The problem is related with orphans. Example:
Both inner objects got ids
1
and2
respectively.This should issues an update, but it is intended to also generate a DELETE for the now orphan courses id 2. This is a similar feature as JPA
orphanRemoval
(more info).How could I get a similar behavior? My first instinct is to use underlying knex to
DELETE
coursesNOT IN
the list of ids I’m saving. A code example would help a lot.Also, I can create a separate issue for orphanRemoval, if you feel that it is within the scope of this project, and not just a help request. 😃
Thanks.