Reputation: 945
I'm using Node.js with Bookshelf to setup an API. The JSON coming in the request looks like this
{
conversation: {
user_ids: [1, 2, 3, 4]
}
}
The conversation object looks like this:
var Conversation = storeManager.bookshelf.Model.extend({
tableName: 'conversations',
users: function() {
this.belongsToMany(User)
}
})
The user looks like this:
var User = storeManager.bookshelf.Model.extend({
tableName: 'users',
conversations: function() {
return this.belongsToMany(Conversation)
}
})
The database has a conversations and users table along with a conversations_users table that has a user_id
and conversation_id
field.
So I've been going through the docs and I'm struggling to figure out how I can create a conversation object that has a relationship with the existing users with the given IDs.
Here is what I have in my controller so far
ConversationController.prototype.create = function(req, res, next) {
// Create the conversation
Conversation.forge().set('users', req.body['conversation']['user_ids']).save().then(function(model) {
req.conversation = model
next()
}).catch(function(err) {
res.status(400).send(err)
})
}
Upvotes: 2
Views: 570
Reputation: 1711
You need to use the add method on your collection like so:
Conversations_Users.add({userId:1,conversation_id:1});
then call
Conversations_Users.save()
Upvotes: 1