How to SELF JOIN using Sequelize in Node

拈花ヽ惹草 提交于 2020-01-15 11:42:30

问题


I'm using sequelize-cli for migrations and have researched different scenarios but there doesn't seem to be a definite solid answer as to how to self join. I want to have a join table called friendships which joins users and friends (which are essentially just users).

More specifically trying to gain an understanding about the difference between "through" and "as" in this situation.

1) This is my friendship table. Getting tripped up on the second association. I have created two columns, one being userId, and one being friendId. I am hoping to be able to have this table linked to 2 users, one in each table, with one column aliased as "friendId".

```

'use strict';
module.exports = function(sequelize, DataTypes) {
  var friendship = sequelize.define('friendship', {
    userId: DataTypes.INTEGER,
    friendId: DataTypes.INTEGER
  }, {
    classMethods: {
      associate: function(models) {
        friendship.belongsTo(models.user);
        friendship.belongsTo(models.user { as: "friend" });
      }
    }
  });
  return friendship;
};

```

2) This is my user model. Again, specifically in the associations object is where I am not clear. The goal here is to be able to call user.friends and have all instances of that user's friends show up. Not certain I am using the "through" and "as" keywords right.

```

'use strict';
module.exports = function(sequelize, DataTypes) {
  var user = sequelize.define('user', {
    username: DataTypes.STRING,
    password: DataTypes.STRING,
    email: DataTypes.STRING
  }, {
    classMethods: {
      associate: function(models) {
        user.hasMany(models.friendship);
        user.hasMany(models.user { as: "friends", through: models.friendship });
      }
    }
  });
  return user;
};

```


回答1:


There is many-to-many relation, it should go through belongsToMany associations, no more relation is needed. There is no need even to define friends table, sequelize will create table automatically

'use strict';
module.exports = function(sequelize, DataTypes) {
      var user = sequelize.define('user', {
        username: DataTypes.STRING,
        password: DataTypes.STRING,
        email: DataTypes.STRING
      }, {
        classMethods: {
          associate: function(models) {
            user.belongsToMany(models.user, {
               as: "friends", 
               through: "friendship", 
               foreignKey: "userId", 
               otherKey: "friendId"
            });
          }
        }
      });
      return user;
};


来源:https://stackoverflow.com/questions/39455380/how-to-self-join-using-sequelize-in-node

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!