使用sequelize通过相同的两个表之间的单独联结表进行查询

时间:2015-08-12 17:27:24

标签: node.js sqlite sequelize.js

SQLite3-我有一个用户表和一个songNodes表。用户可以喜欢的歌曲,用户可以“分叉”歌曲。我有两个单独的联结表,它们按目的表示这些唯一的联系,但其他方面相同。

Sequelize-我知道如何在续集中执行联结查询的唯一方法如下 -

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);
    })
  })
};

我试图对此进行广泛研究,但我无法找到一种方法来指定我想要使用自动生成的函数'getSongNodes'的联结表。任何帮助/指导将不胜感激!

1 个答案:

答案 0 :(得分:2)

我猜你有三个名字分别是User,Song,SongNode。你必须定义这些之间的关联。

您可以定义以下行之类的关联;

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
  }
});

后;你可以使用这样的模型之间的关系;

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

或者你也可以这样;

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

我希望它有效

相关问题