I can't get to work a many-to-many relationship using bookshelf.js.
Models:
var Event = bookshelf.Model.extend({
tableName: 'events',
idAttribute: 'event_id',
tags: function() {
return this.belongsToMany(Tag, 'events_tags', 'event_id', 'tag_id');
}
});
var Tag = bookshelf.Model.extend({
tableName: 'tags',
idAttribute: 'tag_id',
events: function() {
return this.belongsToMany(Event, 'events_tags', 'tag_id', 'event_id');
}
});
Database table "events":
event_id name
-------------------------------------------------
1 party at my place
Database table "tags":
tag_id name
---------------------------
1 music
Database table "events_tags":
event_tag_id event_id tag_id
-------------------------------------------------------------
1 1 1
Query that isn't returning what it should:
new db.Event()
.fetchAll({withRelated: ['tags']})
.then(function(events) {
console.log(events.toJSON());
});
The log outputs:
[{'event_id': 1, 'name': 'party at my place', 'tags': []}]
That is: empty array of tags, which is wrong.
Question: Is there an issue with my code? the desired output should be:
[{
'event_id': 1, 'name': 'party at my place',
'tags': [{'tagId':1, 'name':'music'}]
}]
This doesn't help in the question, but I'll throw it anyway: I'm currently hating all ORMs in Node JS! Maybe I should just use a query builder.
I think I have a similar issue, and had posted about it. Defining a relationship both ways, i.e one from Event to Tag and another from Tag to Event might be creating a deadlock. When the Event definition is being executed, it finds the dependency on Tag and jumps to execute the definition for Tag, inside which there is a dependecy back to Event. At this point they both are not created fully.