3
votes

SQLite3- I have a users table and a songNodes table. A user can favorite songs, and a user can 'fork' songs. I have two separate junction tables that represent these unique by purpose but otherwise identical relationships.

Sequelize- The only way I know how to perform a junction query in sequelize is as follows-

var myForks = function(userId, callback) {
  User.findOne({
    where: {
      id: userId
    }
  })
  .then(function(userObj) {
    userObj.getSongNodes()  //this is where I need to specify
    .then(function(stuff) { //a junction table
      callback(stuff);
    })
  })
};

I have tried to research this extensively and I can not find a way to specify which junction table I want to use with the automatically generated function 'getSongNodes.' Any help/guidance would be greatly appreciated!

1
Can you show the associations as well? - Jan Aagaard Meier
3 many to many relationships between 'users' and 'songNodes' through 'favorite', 'fork', and 'upvote' - tehbigdirty

1 Answers

2
votes

I guess you have three tables which names are User, Song, SongNode. You have to define associations between these.

You can define associations like the following lines;

models.User.belongsToMany(models.Song, {
  "constraints": false,
  "foreignKey": "userId",
  "through": {
    model: models.SongNode,
      unique: false
  }
});

models.Song.belongsToMany(models.User, {
  "constraints": false,
  "foreignKey": "songId",
  "through": {
    model: models.SongNode,
    unique: false
  }
});

After; you can use relations between models like this;

var myForks = function(userId, callback) {
  User
    .findOne({
      "where": { "id": userId }
     })
    .then(function(user) {
      user
        .getSongNodes()
        .then(function(songNodes) {
          callback(songNodes);
        });
    });
};

or you can like this too;

var myForks = function(userId, callback) {
  User
    .findOne({
      "where": { "id": userId },
      "include": [Song]
     })
    .then(function(user) {
      callback(user.Songs);
    });
};

I hope it works